From patchwork Wed Aug 24 11:59:20 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: herron.philip@googlemail.com X-Patchwork-Id: 56977 Return-Path: X-Original-To: patchwork@sourceware.org Delivered-To: patchwork@sourceware.org Received: from server2.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id E6FDF3851143 for ; Wed, 24 Aug 2022 12:00:32 +0000 (GMT) X-Original-To: gcc-patches@gcc.gnu.org Delivered-To: gcc-patches@gcc.gnu.org Received: from mail-wr1-x42d.google.com (mail-wr1-x42d.google.com [IPv6:2a00:1450:4864:20::42d]) by sourceware.org (Postfix) with ESMTPS id ECB8738515FE; Wed, 24 Aug 2022 12:00:14 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.1 sourceware.org ECB8738515FE Authentication-Results: sourceware.org; dmarc=pass (p=quarantine dis=none) header.from=googlemail.com Authentication-Results: sourceware.org; spf=pass smtp.mailfrom=googlemail.com Received: by mail-wr1-x42d.google.com with SMTP id d16so15193771wrr.3; Wed, 24 Aug 2022 05:00:14 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=googlemail.com; s=20210112; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc; bh=vW+oVBrKyKiiJASPTJ3TiwNitoa8EthpxoFCyHSWd/o=; b=UQJmvI3KyD1FHqQGGgXTd3E760BXBudHrBqMy0xQOaObKcv9mKQgVsGcqPE7+6o8Iz ANy50eyUDeqxtUIGPtt6fwtmRCi1QJ0GdqT4gcwWC1oHeYlGBCSYRIOuaSyCnwuWLYt5 8TgWdEFpLnWrTuiH9EibyK3WmfMgHZUIK71lLu2lPEGymDj7Om/JC2trZfKC5mTut4bW R0xv7gc3QedYmmavolL8hjgV3Bf+UEQ2cOOtdU9ePn0QZccZPejOeTT5vQUvagx38Y+n w4uwIxkRq4BHS7J+vwFYPKBG3s0er3o+52QxbUM4YeMJpgAXy2XS/G9UcFTs7tMK8NKf 8uBQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc; bh=vW+oVBrKyKiiJASPTJ3TiwNitoa8EthpxoFCyHSWd/o=; b=rUWE6ccsOl3sedL4b/ZsHDMjgDTdF6qKftU6VWtYSFa0Au/K6sWPLQxXlhxLry3dYt a+JidKqL7zMRye9CZ91a1zdjbJgOvpWoajGk42oFMM3fb6QNtWfM6SJbqmShw2krbcQm b0x2Y3OkirVzroPK+unw7QiQVSqO7nKBmhxUNqtwF/x+Ou44g9paxmzUjVw/37orrdon s/DpPRhPqiF1zzimZROMZa6OZAr8QVfV1Ci4XM4tt5qauPex3ETEcJIXVmZnzEIFgljl 7cINWktDxNIfCemZaQ/ItxR3/N4BTLdC5YUPTAFUAOklrrvISIH4Jqzr2EtNwDCbBJRB LMOw== X-Gm-Message-State: ACgBeo2mDN/ZCl9KyNyNmhR8CDIF+3X7kLzf4tQFXgvHP8tvUEeWexfr xt3JJBTij5/FasaQFj2VnZN21QLxQcQ= X-Google-Smtp-Source: AA6agR6UZ60ikAvqjliVx6dur45qqv6QIJlDKUO7GPs9TqCEAJWj+45eJu/GqpbRimoeDhMyCe/mSQ== X-Received: by 2002:a05:6000:1e0f:b0:225:4052:3a68 with SMTP id bj15-20020a0560001e0f00b0022540523a68mr12089375wrb.707.1661342413389; Wed, 24 Aug 2022 05:00:13 -0700 (PDT) Received: from localhost.localdomain ([86.14.124.218]) by smtp.gmail.com with ESMTPSA id cc19-20020a5d5c13000000b0022571d43d32sm1697676wrb.21.2022.08.24.05.00.12 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 24 Aug 2022 05:00:12 -0700 (PDT) From: herron.philip@googlemail.com X-Google-Original-From: philip.herron@embecosm.com To: gcc-patches@gcc.gnu.org Subject: [PATCH Rust front-end v2 01/37] Use DW_ATE_UTF for the Rust 'char' type Date: Wed, 24 Aug 2022 12:59:20 +0100 Message-Id: <20220824115956.737931-2-philip.herron@embecosm.com> X-Mailer: git-send-email 2.25.1 In-Reply-To: <20220824115956.737931-1-philip.herron@embecosm.com> References: <20220824115956.737931-1-philip.herron@embecosm.com> MIME-Version: 1.0 X-Spam-Status: No, score=-10.6 required=5.0 tests=BAYES_00, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, DKIM_VALID_EF, FREEMAIL_FROM, GIT_PATCH_0, RCVD_IN_DNSWL_NONE, SPF_HELO_NONE, SPF_PASS, TXREP, T_SCC_BODY_TEXT_LINE autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on server2.sourceware.org X-BeenThere: gcc-patches@gcc.gnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: Gcc-patches mailing list List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Reply-To: philip.herron@embecosm.com Cc: gcc-rust@gcc.gnu.org, Tom Tromey Errors-To: gcc-patches-bounces+patchwork=sourceware.org@gcc.gnu.org Sender: "Gcc-patches" From: Tom Tromey The Rust 'char' type should use the DWARF DW_ATE_UTF encoding. --- gcc/dwarf2out.cc | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/gcc/dwarf2out.cc b/gcc/dwarf2out.cc index e3920c898f5..a8bccbabca4 100644 --- a/gcc/dwarf2out.cc +++ b/gcc/dwarf2out.cc @@ -5600,6 +5600,16 @@ is_fortran (const_tree decl) return is_fortran (); } +/* Return TRUE if the language is Rust. */ + +static inline bool +is_rust () +{ + unsigned int lang = get_AT_unsigned (comp_unit_die (), DW_AT_language); + + return lang == DW_LANG_Rust || lang == DW_LANG_Rust_old; +} + /* Return TRUE if the language is Ada. */ static inline bool @@ -13231,7 +13241,11 @@ base_type_die (tree type, bool reverse) } if (TYPE_STRING_FLAG (type)) { - if (TYPE_UNSIGNED (type)) + if ((dwarf_version >= 4 || !dwarf_strict) + && is_rust () + && int_size_in_bytes (type) == 4) + encoding = DW_ATE_UTF; + else if (TYPE_UNSIGNED (type)) encoding = DW_ATE_unsigned_char; else encoding = DW_ATE_signed_char; @@ -25201,6 +25215,13 @@ gen_compile_unit_die (const char *filename) } else if (strcmp (language_string, "GNU F77") == 0) language = DW_LANG_Fortran77; + else if (strcmp (language_string, "GNU Rust") == 0) + { + if (dwarf_version >= 5 || !dwarf_strict) + language = DW_LANG_Rust; + else + language = DW_LANG_Rust_old; + } else if (dwarf_version >= 3 || !dwarf_strict) { if (strcmp (language_string, "GNU Ada") == 0) From patchwork Wed Aug 24 11:59:21 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: herron.philip@googlemail.com X-Patchwork-Id: 56978 Return-Path: X-Original-To: patchwork@sourceware.org Delivered-To: patchwork@sourceware.org Received: from server2.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id 6DA723850212 for ; Wed, 24 Aug 2022 12:01:07 +0000 (GMT) X-Original-To: gcc-patches@gcc.gnu.org Delivered-To: gcc-patches@gcc.gnu.org Received: from mail-wr1-x433.google.com (mail-wr1-x433.google.com [IPv6:2a00:1450:4864:20::433]) by sourceware.org (Postfix) with ESMTPS id 216C2385043C; Wed, 24 Aug 2022 12:00:26 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.1 sourceware.org 216C2385043C Authentication-Results: sourceware.org; dmarc=pass (p=quarantine dis=none) header.from=googlemail.com Authentication-Results: sourceware.org; spf=pass smtp.mailfrom=googlemail.com Received: by mail-wr1-x433.google.com with SMTP id h5so19676040wru.7; Wed, 24 Aug 2022 05:00:26 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=googlemail.com; s=20210112; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc; bh=IsTU1wqw8+1bgoubFz+cWEDaOKQuY/K1Id53/TusWK8=; b=A1Y4r5OQZyWkF5ixJWtiSFKxZyB6qScycKdNsqrNZjNaWXIRfeS7WnRokR4LrHVjHX CHKEfKd6jUWjebbphotDidQzKbLUWvs86mEXiocHDzSssTXhltnc+RqznpaxV2lC5cMy A+J1Me1B3hS5LOiwJG6QJea3zFtThVNJQpp4ubi0S52XwkR4NMwiLL5EvpUYs5JHen6B uXQ/4NMcUXQBt/cGluOc6MNdHpHSQT72rkQEgqADB14veL4S/tJbjJzKG9bcATARvN5h 10FcNlp5YV0RG/z0jY3VdnqaZ7HhTWQ1k4Lh1ExG/GnzteKxr87FOUU9u1YIGjXxyNwX jcrg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc; bh=IsTU1wqw8+1bgoubFz+cWEDaOKQuY/K1Id53/TusWK8=; b=10LqdI6SBhTaodNjx8B+nhZmeOjxtK/w8c0THcLE4OGCZMTQwiVLTemmJFGx9QrQAy IaDiLmFQnsx+xq7A+3DjpJkatLGq3tABOo+rtSFWUzIlgyXYymj9imQsd4Vs5BVCXO3B 4N/CtPZ1rPdO4AY4abnGbf2ZMu06CCSRZELxROkG4wnjlF76pxWF+/W/Os4kIXyfZ4Tr 0g+QHWP481lSFaqaygpjOrrPZJ0h4SXAA/fu8a8e2vJx/ag7ArlR+Wfr2VZRTsefYNaj ih42KeBwNsHVy3220ZN9YTA+aeKNjVDtISzdNqvJY6MuqgKtjqDsYvcKAFCVs/JA/Spf OjzQ== X-Gm-Message-State: ACgBeo1KGack/qgKXxe0IhojFfv+q3tiY+5N5iMGtygN22GtRgQOI9zQ 7IiOSc+ooDDAMD5in0XTvVwxaaMJaXc= X-Google-Smtp-Source: AA6agR4aRHZBJ+VGHD0PXpo8W/DPev8dyDpgQgORSQkA1kVbJ+ppi+lnnuuTLQql3aJhDZWK/GyOgw== X-Received: by 2002:a05:6000:250:b0:225:624b:13 with SMTP id m16-20020a056000025000b00225624b0013mr5711899wrz.127.1661342424558; Wed, 24 Aug 2022 05:00:24 -0700 (PDT) Received: from localhost.localdomain ([86.14.124.218]) by smtp.gmail.com with ESMTPSA id cc19-20020a5d5c13000000b0022571d43d32sm1697676wrb.21.2022.08.24.05.00.23 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 24 Aug 2022 05:00:23 -0700 (PDT) From: herron.philip@googlemail.com X-Google-Original-From: philip.herron@embecosm.com To: gcc-patches@gcc.gnu.org Subject: [PATCH Rust front-end v2 02/37] gccrs: Add nessecary hooks for a Rust front-end testsuite Date: Wed, 24 Aug 2022 12:59:21 +0100 Message-Id: <20220824115956.737931-3-philip.herron@embecosm.com> X-Mailer: git-send-email 2.25.1 In-Reply-To: <20220824115956.737931-1-philip.herron@embecosm.com> References: <20220824115956.737931-1-philip.herron@embecosm.com> MIME-Version: 1.0 X-Spam-Status: No, score=-10.8 required=5.0 tests=BAYES_00, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, DKIM_VALID_EF, FREEMAIL_FROM, GIT_PATCH_0, KAM_SHORT, RCVD_IN_DNSWL_NONE, SPF_HELO_NONE, SPF_PASS, TXREP, T_SCC_BODY_TEXT_LINE autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on server2.sourceware.org X-BeenThere: gcc-patches@gcc.gnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: Gcc-patches mailing list List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Reply-To: philip.herron@embecosm.com Cc: gcc-rust@gcc.gnu.org, Philip Herron , Thomas Schwinge , =?utf-8?q?Marc_Poulhi=C3=A8s?= Errors-To: gcc-patches-bounces+patchwork=sourceware.org@gcc.gnu.org Sender: "Gcc-patches" From: Philip Herron This copy's over code from other front-end testsuites to enable testing for the rust front-end specifically. Co-authored-by: Marc Poulhiès Co-authored-by: Thomas Schwinge --- gcc/testsuite/lib/rust-dg.exp | 49 +++++++++ gcc/testsuite/lib/rust.exp | 186 ++++++++++++++++++++++++++++++++++ 2 files changed, 235 insertions(+) create mode 100644 gcc/testsuite/lib/rust-dg.exp create mode 100644 gcc/testsuite/lib/rust.exp diff --git a/gcc/testsuite/lib/rust-dg.exp b/gcc/testsuite/lib/rust-dg.exp new file mode 100644 index 00000000000..a8a2ac0c8eb --- /dev/null +++ b/gcc/testsuite/lib/rust-dg.exp @@ -0,0 +1,49 @@ +# Copyright (C) 1997-2022 Free Software Foundation, Inc. + +# This program 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 of the License, or +# (at your option) any later version. +# +# This program 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 +# . + +load_lib gcc-dg.exp + +# Define rust callbacks for dg.exp. + +proc rust-dg-test { prog do_what extra_tool_flags } { + return [gcc-dg-test-1 rust_target_compile $prog $do_what $extra_tool_flags] +} + +proc rust-dg-prune { system text } { + return [gcc-dg-prune $system $text] +} + +# Utility routines. + +# +# rust_load -- wrapper around default rust_load to handle tests that +# require program arguments passed to them. +# + +if { [info procs rust_load] != [list] \ + && [info procs prev_rust_load] == [list] } { + rename rust_load prev_rust_load + + proc rust_load { program args } { + global RUST_EXECUTE_ARGS + if [info exists RUST_EXECUTE_ARGS] then { + set args [concat "{$RUST_EXECUTE_ARGS}"] + } + set result [eval [list prev_rust_load $program] $args ] + return $result + } +} + diff --git a/gcc/testsuite/lib/rust.exp b/gcc/testsuite/lib/rust.exp new file mode 100644 index 00000000000..6993c976304 --- /dev/null +++ b/gcc/testsuite/lib/rust.exp @@ -0,0 +1,186 @@ +# Copyright (C) 2012-2022 Free Software Foundation, Inc. + +# This program 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 of the License, or +# (at your option) any later version. +# +# This program 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 +# . + +# +# rust support library routines +# + +load_lib prune.exp +load_lib gcc-defs.exp +load_lib timeout.exp +load_lib target-libpath.exp + +# +# RUST_UNDER_TEST is the compiler under test. +# + +set rust_compile_options "" + + +# +# rust_include_flags -- include flags for the gcc tree structure +# + +proc rust_include_flags { paths } { + global srcdir + global TESTING_IN_BUILD_TREE + + set flags "" + + if { [is_remote host] || ![info exists TESTING_IN_BUILD_TREE] } { + return "${flags}" + } + + set gccpath ${paths} + + return "$flags" +} + +# +# rust_link_flags -- linker flags for the gcc tree structure +# + +proc rust_link_flags { paths } { + global srcdir + global ld_library_path + global RUST_UNDER_TEST + global shlib_ext + global SHARED_OPTION + + set gccpath ${paths} + set libio_dir "" + set flags "" + set ld_library_path "." + set shlib_ext [get_shlib_extension] + set SHARED_OPTION "" + verbose "shared lib extension: $shlib_ext" + + set_ld_library_path_env_vars + + return "$flags" +} + +# +# rust_init -- called at the start of each subdir of tests +# + +proc rust_init { args } { + global subdir + global rust_initialized + global base_dir + global tmpdir + global libdir + global gluefile wrap_flags + global objdir srcdir + global ALWAYS_RUSTFLAGS + global TOOL_EXECUTABLE TOOL_OPTIONS + global RUST_UNDER_TEST + global TESTING_IN_BUILD_TREE + global TEST_ALWAYS_FLAGS + global gcc_warning_prefix + global gcc_error_prefix + + # We set LC_ALL and LANG to C so that we get the same error messages as expected. + setenv LC_ALL C + setenv LANG C + + if ![info exists RUST_UNDER_TEST] then { + if [info exists TOOL_EXECUTABLE] { + set RUST_UNDER_TEST $TOOL_EXECUTABLE + } else { + if { [is_remote host] || ! [info exists TESTING_IN_BUILD_TREE] } { + set RUST_UNDER_TEST [transform gccrs] + } else { + set RUST_UNDER_TEST [findfile $base_dir/../../gccrs "$base_dir/../../gccrs -B$base_dir/../../" [findfile $base_dir/gccrs "$base_dir/gccrs -B$base_dir/" [transform gccrs]]] + } + } + } + + if ![is_remote host] { + if { [which $RUST_UNDER_TEST] == 0 } then { + perror "RUST_UNDER_TEST ($RUST_UNDER_TEST) does not exist" + exit 1 + } + } + + if ![info exists tmpdir] { + set tmpdir "/tmp" + } + + if [info exists gluefile] { + unset gluefile + } + + rust_maybe_build_wrapper "${tmpdir}/rust-testglue.o" + + set ALWAYS_RUSTFLAGS "" + + # TEST_ALWAYS_FLAGS are flags that should be passed to every + # compilation. They are passed first to allow individual + # tests to override them. + if [info exists TEST_ALWAYS_FLAGS] { + lappend ALWAYS_RUSTFLAGS "additional_flags=$TEST_ALWAYS_FLAGS" + } + + if ![is_remote host] { + if [info exists TOOL_OPTIONS] { + lappend ALWAYS_RUSTFLAGS "additional_flags=[rust_include_flags [get_multilibs ${TOOL_OPTIONS}] ]" + lappend ALWAYS_RUSTFLAGS "ldflags=[rust_link_flags [get_multilibs ${TOOL_OPTIONS}] ]" + } else { + lappend ALWAYS_RUSTFLAGS "additional_flags=[rust_include_flags [get_multilibs] ]" + lappend ALWAYS_RUSTFLAGS "ldflags=[rust_link_flags [get_multilibs] ]" + } + } + + if [info exists TOOL_OPTIONS] { + lappend ALWAYS_RUSTFLAGS "additional_flags=$TOOL_OPTIONS" + } + + verbose -log "ALWAYS_RUSTFLAGS set to $ALWAYS_RUSTFLAGS" + + set gcc_warning_prefix "warning:" + set gcc_error_prefix "(fatal )?error:" + + verbose "rust is initialized" 3 +} + +# +# rust_target_compile -- compile a source file +# + +proc rust_target_compile { source dest type options } { + global tmpdir + global gluefile wrap_flags + global ALWAYS_RUSTFLAGS + global RUST_UNDER_TEST + global individual_timeout + + # HACK: guard against infinite loops in the compiler + set individual_timeout 10 + + if { [target_info needs_status_wrapper] != "" && [info exists gluefile] } { + lappend options "libs=${gluefile}" + lappend options "ldflags=${wrap_flags}" + } + + lappend options "timeout=[timeout_value]" + lappend options "compiler=$RUST_UNDER_TEST" + + set options [concat "$ALWAYS_RUSTFLAGS" $options] + set options [dg-additional-files-options $options $source] + + return [target_compile $source $dest $type $options] +} From patchwork Wed Aug 24 11:59:22 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: herron.philip@googlemail.com X-Patchwork-Id: 56980 Return-Path: X-Original-To: patchwork@sourceware.org Delivered-To: patchwork@sourceware.org Received: from server2.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id C871C384D1A9 for ; Wed, 24 Aug 2022 12:01:41 +0000 (GMT) X-Original-To: gcc-patches@gcc.gnu.org Delivered-To: gcc-patches@gcc.gnu.org Received: from mail-wm1-x330.google.com (mail-wm1-x330.google.com [IPv6:2a00:1450:4864:20::330]) by sourceware.org (Postfix) with ESMTPS id 7CF6A385023F; Wed, 24 Aug 2022 12:00:29 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.1 sourceware.org 7CF6A385023F Authentication-Results: sourceware.org; dmarc=pass (p=quarantine dis=none) header.from=googlemail.com Authentication-Results: sourceware.org; spf=pass smtp.mailfrom=googlemail.com Received: by mail-wm1-x330.google.com with SMTP id j26so8670933wms.0; Wed, 24 Aug 2022 05:00:29 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=googlemail.com; s=20210112; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc; bh=p4JDD1WbIQhaecFaGqVIjJdoG7TAeLt5iH/ZmRxdkuI=; b=QJ6iqqxlyOcyK1bIntgZo2xuWktOsaorFHi4/9iwAOMAT6YnUh3Sxdo3qz5h+/DJ+r FIpPgfpZRq0+gjGFZ2mR5BlXJ4Sj7//eUXQTthloyCbO9DPOIaUyCbbxXRH/SIycvBKF Wo3tCwtBGViyD0gyn1ZMRbVp0O7vQ6WOA1QK2D2BFaef5tivsnXRFaX5ODxR1cdXH2iD SB4+X9Q0MjMuXJuxchPB2jFrthiFMRs6NSiHeH262I+Nt7VaUftRfglWAdY79n3xL8FQ 4K1Fot7que1SwLJDuDzz03K7fMUxaMPNPD1UHdoVBiQdFNqngSERw6D2UXnZVxy7l4Um VAjw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc; bh=p4JDD1WbIQhaecFaGqVIjJdoG7TAeLt5iH/ZmRxdkuI=; b=nJBgEQ67mEcKOXRSc2EJrdB+P3VT6j0pDVQaWhSXAGchtWN2FjlPGtvK03knpzwX2T HPtj3uKUTQLfUUCm2uM7JEA9g9C2HbQLVShpxR8Y0I/EndA2buXFuprDg9eqrT9jqoIt h+xxnyw28Jf9oY/EhVQ3Yir3vIoRM+lIDGbgxZ7wI9xAZje9r9aAJzvha6PS/UvsGPxJ tz+3gDctdRGmzggzFgZ5i4vHYf7Nq0fJC3Wb3pvq6E7SWyfaJ59o/9Jo96ISkO1N4+FR PBKrFhu+qCcSKjaIyjGqs9czvlIrOMzDbmCwHolUEESKa9K7bWWyeCbOOeGF3mq9Oxfj zQVQ== X-Gm-Message-State: ACgBeo3VhJXqJ1xcSuSkj3tHzgq1pQ7B3XZMfZzvuK+z8EptsLWsLr2C 3lmqjGst/iKDcD5f2klBjmfC6TyIs04= X-Google-Smtp-Source: AA6agR7lW9hgwQYAws18zx4Q4jCszY0CFcGQNzL26zZDVg5Ak2lx4pG649S71odQRqACmKPup/bn0w== X-Received: by 2002:a1c:7916:0:b0:3a6:3540:5b3c with SMTP id l22-20020a1c7916000000b003a635405b3cmr4923175wme.178.1661342428057; Wed, 24 Aug 2022 05:00:28 -0700 (PDT) Received: from localhost.localdomain ([86.14.124.218]) by smtp.gmail.com with ESMTPSA id cc19-20020a5d5c13000000b0022571d43d32sm1697676wrb.21.2022.08.24.05.00.26 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 24 Aug 2022 05:00:27 -0700 (PDT) From: herron.philip@googlemail.com X-Google-Original-From: philip.herron@embecosm.com To: gcc-patches@gcc.gnu.org Subject: [PATCH Rust front-end v2 03/37] gccrs: Add Debug info testsuite Date: Wed, 24 Aug 2022 12:59:22 +0100 Message-Id: <20220824115956.737931-4-philip.herron@embecosm.com> X-Mailer: git-send-email 2.25.1 In-Reply-To: <20220824115956.737931-1-philip.herron@embecosm.com> References: <20220824115956.737931-1-philip.herron@embecosm.com> MIME-Version: 1.0 X-Spam-Status: No, score=-11.0 required=5.0 tests=BAYES_00, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, DKIM_VALID_EF, FREEMAIL_FROM, GIT_PATCH_0, KAM_SHORT, RCVD_IN_DNSWL_NONE, SPF_HELO_NONE, SPF_PASS, TXREP, T_SCC_BODY_TEXT_LINE autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on server2.sourceware.org X-BeenThere: gcc-patches@gcc.gnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: Gcc-patches mailing list List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Reply-To: philip.herron@embecosm.com Cc: gcc-rust@gcc.gnu.org, Philip Herron , Tom Tromey Errors-To: gcc-patches-bounces+patchwork=sourceware.org@gcc.gnu.org Sender: "Gcc-patches" From: Philip Herron This testsuite is specifically about testcases which scan the asm debug info for results. Co-authored-by: Tom Tromey --- gcc/testsuite/rust/debug/chartype.rs | 10 ++++++ .../rust/debug/custom_link_section.rs | 13 ++++++++ gcc/testsuite/rust/debug/debug.exp | 33 +++++++++++++++++++ gcc/testsuite/rust/debug/i8u8.rs | 12 +++++++ gcc/testsuite/rust/debug/lang.rs | 6 ++++ gcc/testsuite/rust/debug/no_mangle.rs | 17 ++++++++++ gcc/testsuite/rust/debug/oldlang.rs | 6 ++++ gcc/testsuite/rust/debug/tuple.rs | 8 +++++ gcc/testsuite/rust/debug/win64-abi.rs | 11 +++++++ 9 files changed, 116 insertions(+) create mode 100644 gcc/testsuite/rust/debug/chartype.rs create mode 100644 gcc/testsuite/rust/debug/custom_link_section.rs create mode 100644 gcc/testsuite/rust/debug/debug.exp create mode 100644 gcc/testsuite/rust/debug/i8u8.rs create mode 100644 gcc/testsuite/rust/debug/lang.rs create mode 100644 gcc/testsuite/rust/debug/no_mangle.rs create mode 100644 gcc/testsuite/rust/debug/oldlang.rs create mode 100644 gcc/testsuite/rust/debug/tuple.rs create mode 100644 gcc/testsuite/rust/debug/win64-abi.rs diff --git a/gcc/testsuite/rust/debug/chartype.rs b/gcc/testsuite/rust/debug/chartype.rs new file mode 100644 index 00000000000..69e7ab0b17f --- /dev/null +++ b/gcc/testsuite/rust/debug/chartype.rs @@ -0,0 +1,10 @@ +// 'char' should use DW_ATE_UTF +fn main () { + let c = 'x'; +// { dg-do compile } +// Use -w to avoid warnings about the unused variables +// DW_ATE_UTF entered in DWARF 4. +// { dg-options "-w -gdwarf-4 -dA" } +// DW_ATE_UTF = 0x10 +// { dg-final { scan-assembler "0x10\[ \t]\[^\n\r]* DW_AT_encoding" } } */ +} diff --git a/gcc/testsuite/rust/debug/custom_link_section.rs b/gcc/testsuite/rust/debug/custom_link_section.rs new file mode 100644 index 00000000000..142f3513136 --- /dev/null +++ b/gcc/testsuite/rust/debug/custom_link_section.rs @@ -0,0 +1,13 @@ +#[link_section = ".universe"] +fn not_in_text() -> i32 { + 42 +} + +fn main() -> i32 { +// { dg-do compile } +// { dg-options "-gdwarf-5 -dA -w" } + not_in_text(); +// { dg-final { scan-assembler ".universe" } } */ + + 0 +} diff --git a/gcc/testsuite/rust/debug/debug.exp b/gcc/testsuite/rust/debug/debug.exp new file mode 100644 index 00000000000..c71b5930d90 --- /dev/null +++ b/gcc/testsuite/rust/debug/debug.exp @@ -0,0 +1,33 @@ +# Copyright (C) 2021-2022 Free Software Foundation, Inc. + +# This program 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 of the License, or +# (at your option) any later version. +# +# This program 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 +# . + +# Debugging tests. + +# Load support procs. +load_lib rust-dg.exp + +# Initialize `dg'. +dg-init + +# Main loop. +set saved-dg-do-what-default ${dg-do-what-default} + +set dg-do-what-default "compile" +dg-runtest [lsort [glob -nocomplain $srcdir/$subdir/*.rs]] "" "" +set dg-do-what-default ${saved-dg-do-what-default} + +# All done. +dg-finish diff --git a/gcc/testsuite/rust/debug/i8u8.rs b/gcc/testsuite/rust/debug/i8u8.rs new file mode 100644 index 00000000000..1cd21a4a8ff --- /dev/null +++ b/gcc/testsuite/rust/debug/i8u8.rs @@ -0,0 +1,12 @@ +// i8 and u8 types should not have the DWARF 'char' encoding. +fn main () { + let x : i8 = 5; + let y : u8 = 7; +// { dg-do compile } +// Use -w to avoid warnings about the unused variables +// { dg-options "-w -g -dA" } +// DW_ATE_signed_char = 6 +// { dg-final { scan-assembler-not "0x6\[ \t]\[^\n\r]* DW_AT_encoding" } } */ +// DW_ATE_unsigned_char = 8 +// { dg-final { scan-assembler-not "0x8\[ \t]\[^\n\r]* DW_AT_encoding" } } */ +} diff --git a/gcc/testsuite/rust/debug/lang.rs b/gcc/testsuite/rust/debug/lang.rs new file mode 100644 index 00000000000..12e0b587a02 --- /dev/null +++ b/gcc/testsuite/rust/debug/lang.rs @@ -0,0 +1,6 @@ +fn main () { +// { dg-do compile } +// { dg-options "-gdwarf-5 -dA" } +// DW_LANG_Rust is 0x1c +// { dg-final { scan-assembler "0x1c\[ \t]\[^\n\r]* DW_AT_language" } } */ +} diff --git a/gcc/testsuite/rust/debug/no_mangle.rs b/gcc/testsuite/rust/debug/no_mangle.rs new file mode 100644 index 00000000000..0cef40482f4 --- /dev/null +++ b/gcc/testsuite/rust/debug/no_mangle.rs @@ -0,0 +1,17 @@ +#[no_mangle] +fn do_not_mangle() -> i32 { + 0 +} + +fn please_mangle() {} + +fn main() { +// { dg-do compile } +// { dg-options "-gdwarf-5 -dA" } + let _ = do_not_mangle(); + please_mangle(); +// look for unmangled function name: +// { dg-final { scan-assembler "do_not_mangle:" } } */ +// look for legacy mangled function name: +// { dg-final { scan-assembler "13please_mangle" } } */ +} diff --git a/gcc/testsuite/rust/debug/oldlang.rs b/gcc/testsuite/rust/debug/oldlang.rs new file mode 100644 index 00000000000..ddacf0e4392 --- /dev/null +++ b/gcc/testsuite/rust/debug/oldlang.rs @@ -0,0 +1,6 @@ +fn main () { +// { dg-do compile } +// { dg-options "-gstrict-dwarf -gdwarf-3 -dA" } +// DW_LANG_Rust_old is 0x9000 +// { dg-final { scan-assembler "0x9000\[ \t]\[^\n\r]* DW_AT_language" } } */ +} diff --git a/gcc/testsuite/rust/debug/tuple.rs b/gcc/testsuite/rust/debug/tuple.rs new file mode 100644 index 00000000000..e51a5ffdbb6 --- /dev/null +++ b/gcc/testsuite/rust/debug/tuple.rs @@ -0,0 +1,8 @@ +fn main () { +// { dg-do compile } +// { dg-options "-gdwarf-5 -dA -w" } + let x = (32, 32); +// Look for field __0 and __1 +// { dg-final { scan-assembler "__0" } } */ +// { dg-final { scan-assembler "__1" } } */ +} diff --git a/gcc/testsuite/rust/debug/win64-abi.rs b/gcc/testsuite/rust/debug/win64-abi.rs new file mode 100644 index 00000000000..b2b08cd5114 --- /dev/null +++ b/gcc/testsuite/rust/debug/win64-abi.rs @@ -0,0 +1,11 @@ +// { dg-do compile { target { x86_64-*-* } } } +// { dg-options "-gdwarf-5 -dA -w -O1 -m64" } +pub extern "win64" fn square(num: i32) -> i32 { + num * num +} + +fn main() { + // MS ABI dictates that the first argument is ecx instead of edi from the sysv world + // { dg-final { scan-assembler "%ecx, %ecx" } } + square(1); +} From patchwork Wed Aug 24 11:59:23 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: herron.philip@googlemail.com X-Patchwork-Id: 56983 Return-Path: X-Original-To: patchwork@sourceware.org Delivered-To: patchwork@sourceware.org Received: from server2.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id 2CD5C384B121 for ; Wed, 24 Aug 2022 12:02:24 +0000 (GMT) X-Original-To: gcc-patches@gcc.gnu.org Delivered-To: gcc-patches@gcc.gnu.org Received: from mail-wr1-x436.google.com (mail-wr1-x436.google.com [IPv6:2a00:1450:4864:20::436]) by sourceware.org (Postfix) with ESMTPS id C6CE6384D19E; Wed, 24 Aug 2022 12:00:30 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.1 sourceware.org C6CE6384D19E Authentication-Results: sourceware.org; dmarc=pass (p=quarantine dis=none) header.from=googlemail.com Authentication-Results: sourceware.org; spf=pass smtp.mailfrom=googlemail.com Received: by mail-wr1-x436.google.com with SMTP id z16so1688794wrh.10; Wed, 24 Aug 2022 05:00:30 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=googlemail.com; s=20210112; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc; bh=UoinBedO3DC9KUT7KTx0GF4jy1PPEGkTBIUBYtOTP1w=; b=HEEQoyZ2+MlT6nyEAZ2gJoJG/abRNniY9U9LZQfOh97CMFhd2zm4UxEwHkztgjHNmf MQLs9PbSDF4UukUFvVKQa8JLVac+HhBbLDnE9YHNhbvSrrNw3yckKesUim+VruslH4sq SZm+pXCh9tNUljGa3R7KzkBfeCdPBCZ6TM8JfiG17/27BZy8O5lS81Ik3wMoz1u4KAdL u3wCe74JTnOhfpbWUA0s2MCE9oDQQzGV0O82xEAJs3EeK2Bov9qG5wDcBhJ0TvU1Diu4 SvrzsGTyUhXDl6eX1YsyOGlfnp4ep8Kx4AOK8V+cBf4kA0xqyOC+YuppdoO2gNAFQ7Qc t+iQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc; bh=UoinBedO3DC9KUT7KTx0GF4jy1PPEGkTBIUBYtOTP1w=; b=IPid/BEFvTEejENrgVIxQZWcpnN5fvI8J65ZmggVH4Gl+cN2Yxg4vGZPoCayMhdJbE HbvdhnG7eX95yHlI3MjrZ21Umdgi0CvLZt0BXw6+m2d8XSta9g4FMTCJjMIcFU3+dJax lYfvNlpbVauOKUCoULaNjcvczlAP5du1pZLZRCQfrxh9gSMZ9bphASbEnAV0gUcgO7WE eBn6NtABzaTnA6h3ixskzSv+BtCQ+WCfrAbz6vGUslCsERQ0NpwWmeGjFRmKIdD9Bhve hSteN830JJ17s6T7LR5lrGS1whoALKjvIN2z6aGrdHjKQKDVYEoci5hmkiLtH+tDZUbA gcow== X-Gm-Message-State: ACgBeo0EkvQs2DtAUijTfZCPG9XjYhDQa3uoDba2zKA+9KN+7ER1RmRm 42XEVXntpUFCNRRHetD7ysQuAoOZl/Q= X-Google-Smtp-Source: AA6agR7wx/BPHDsbWDOM/fQmSANCJBthsWgrb+VGeZzZI3k/rVQhGKdgpWebzRwG7VFRQFSKbKvRKA== X-Received: by 2002:a5d:67c6:0:b0:225:2a3e:6384 with SMTP id n6-20020a5d67c6000000b002252a3e6384mr15660204wrw.23.1661342429988; Wed, 24 Aug 2022 05:00:29 -0700 (PDT) Received: from localhost.localdomain ([86.14.124.218]) by smtp.gmail.com with ESMTPSA id cc19-20020a5d5c13000000b0022571d43d32sm1697676wrb.21.2022.08.24.05.00.28 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 24 Aug 2022 05:00:29 -0700 (PDT) From: herron.philip@googlemail.com X-Google-Original-From: philip.herron@embecosm.com To: gcc-patches@gcc.gnu.org Subject: [PATCH Rust front-end v2 04/37] gccrs: Add link cases testsuite Date: Wed, 24 Aug 2022 12:59:23 +0100 Message-Id: <20220824115956.737931-5-philip.herron@embecosm.com> X-Mailer: git-send-email 2.25.1 In-Reply-To: <20220824115956.737931-1-philip.herron@embecosm.com> References: <20220824115956.737931-1-philip.herron@embecosm.com> MIME-Version: 1.0 X-Spam-Status: No, score=-11.1 required=5.0 tests=BAYES_00, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, DKIM_VALID_EF, FREEMAIL_FROM, GIT_PATCH_0, KAM_SHORT, RCVD_IN_DNSWL_NONE, SPF_HELO_NONE, SPF_PASS, TXREP, T_SCC_BODY_TEXT_LINE autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on server2.sourceware.org X-BeenThere: gcc-patches@gcc.gnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: Gcc-patches mailing list List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Reply-To: philip.herron@embecosm.com Cc: gcc-rust@gcc.gnu.org, Philip Herron Errors-To: gcc-patches-bounces+patchwork=sourceware.org@gcc.gnu.org Sender: "Gcc-patches" From: Philip Herron This testsuite is heavily inspired from the lto testsuite which uses a pattern that each file is compiled to an object file and finally linked together. Since rust does not have headers/prototypes we rely on the ordering here so that all files numbered greater than zero get compiled to object files first leaving the _0 file free to test the 'extern crate' and use keywords to force testing of the compiler to read metadata from the other 'crates'. --- gcc/testsuite/rust/link/generic_function_0.rs | 7 + gcc/testsuite/rust/link/generic_function_1.rs | 3 + gcc/testsuite/rust/link/link.exp | 172 ++++++++++++++++++ gcc/testsuite/rust/link/simple_function_0.rs | 8 + gcc/testsuite/rust/link/simple_function_1.rs | 3 + gcc/testsuite/rust/link/trait_import_0.rs | 19 ++ gcc/testsuite/rust/link/trait_import_1.rs | 6 + 7 files changed, 218 insertions(+) create mode 100644 gcc/testsuite/rust/link/generic_function_0.rs create mode 100644 gcc/testsuite/rust/link/generic_function_1.rs create mode 100644 gcc/testsuite/rust/link/link.exp create mode 100644 gcc/testsuite/rust/link/simple_function_0.rs create mode 100644 gcc/testsuite/rust/link/simple_function_1.rs create mode 100644 gcc/testsuite/rust/link/trait_import_0.rs create mode 100644 gcc/testsuite/rust/link/trait_import_1.rs diff --git a/gcc/testsuite/rust/link/generic_function_0.rs b/gcc/testsuite/rust/link/generic_function_0.rs new file mode 100644 index 00000000000..58b8eb13db6 --- /dev/null +++ b/gcc/testsuite/rust/link/generic_function_0.rs @@ -0,0 +1,7 @@ +extern crate generic_function_1; +use generic_function_1::generic_function; + +fn main() -> i32 { + let a = generic_function(123); + a - 123 +} diff --git a/gcc/testsuite/rust/link/generic_function_1.rs b/gcc/testsuite/rust/link/generic_function_1.rs new file mode 100644 index 00000000000..8fb0788e388 --- /dev/null +++ b/gcc/testsuite/rust/link/generic_function_1.rs @@ -0,0 +1,3 @@ +pub fn generic_function(a: X) -> X { + a +} diff --git a/gcc/testsuite/rust/link/link.exp b/gcc/testsuite/rust/link/link.exp new file mode 100644 index 00000000000..8b2e93ceab6 --- /dev/null +++ b/gcc/testsuite/rust/link/link.exp @@ -0,0 +1,172 @@ +# Copyright (C) 2021-2022 Free Software Foundation, Inc. + +# This program 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 of the License, or +# (at your option) any later version. +# +# This program 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 +# . + +# Execute tests, torture testing. + +# Load support procs. +load_lib rust-dg.exp + +# Initialize `dg'. +dg-init + +# Main loop. +set saved-dg-do-what-default ${dg-do-what-default} + +set dg-do-what-default "assemble" + +# rs-obj -- compile to an object file +# +# SOURCE is the source file +# DEST is the object file +# OPTALL is the list of compiler options to use with all tests +# OPTFILE is the list of compiler options to use with this file +# OPTSTR is the options to print with test messages +# XFAILDATA is the xfail data to be passed to the compiler +proc rs-obj { source dest optall optfile optstr xfaildata } { + global tool + global compiler_conditional_xfail_data + + # Set up the options for compiling this file. + set options "" + lappend options "additional_flags=$optall $optfile" + + set compiler_conditional_xfail_data $xfaildata + set comp_output [${tool}_target_compile "$source" "$dest" object $options] +} + +# rs-execute -- compile multi-file tests +# +# SRC1 is the full pathname of the main file of the testcase. +# SID identifies a test suite in the names of temporary files. +proc rs-execute-1 { src1 } { + global srcdir tmpdir + + # Get extra flags for this test from the primary source file, and + # process other dg-* options that this suite supports. Warn about + # unsupported flags. + verbose "rs-execute: $src1" 1 + set compile_type "run" + set compile_xfail(0) "" + + # Set up the names of the other source files. + set dir [file dirname $src1] + set base [file rootname $src1] + set base [string range $base [string length $dir] end] + regsub "_0" $base "" base + regsub "/" $base "" base + set src_list $src1 + set i 1 + set done 0 + while { !$done } { + set names [glob -nocomplain -types f -- "${dir}/${base}_${i}.*"] + if { [llength ${names}] > 1 } { + warning "rs-link-execute: more than one file matched ${dir}/${base}_${i}.*" + } + if { [llength ${names}] == 1 } { + lappend src_list [lindex ${names} 0] + incr i + } else { + set num_srcs ${i} + set done 1 + } + } + + + # Define the names of the object files. + set obj_list "" + for {set i 0} {$i < $num_srcs} {incr i} { + lappend obj_list "${base}_${i}.o" + } + + # Get the base name of this test, for use in messages. + set testcase [lindex ${src_list} 0] + + # Remove the $srcdir and $tmpdir prefixes from $src1. (It would + # be possible to use "regsub" here, if we were careful to escape + # all regular expression characters in $srcdir and $tmpdir, but + # that would be more complicated that this approach.) + if {[string first "$srcdir/" "${testcase}"] == 0} { + set testcase [string range "${testcase}" [string length "$srcdir/"] end] + } + if {[string first "$tmpdir/" "$testcase"] == 0} { + set testcase [string range "$testcase" [string length "$tmpdir/"] end] + set testcase "tmpdir-$testcase" + } + # If we couldn't rip $srcdir out of `src1' then just do the best we can. + # The point is to reduce the unnecessary noise in the logs. Don't strip + # out too much because different testcases with the same name can confuse + # `test-tool'. + if [string match "/*" $testcase] then { + set testcase "[file tail [file dirname $src1]]/[file tail $src1]" + } + + # Set up the base name of executable files so they'll be unique. + regsub -all "\[./\]" $testcase "-" execbase + + verbose "Testing $testcase - $obj_list - $src_list" + + # There's a unique name for each executable we generate. + set execname "${execbase}-1.exe" + + # The LTO tests don't use dg-test, so testname_with_flags and + # output_file need to be defined explicitly for each file. scan-symbol + # directives rely on both of these to be defined to find the symbol to + # scan and for the text to print in the PASS/FAIL since they can also + # be called from dg-test. testname_with_flags is also used via + # testname-for-summary when calling into generic function below to + # clean temporary files. + set output_file $execname + set testname_with_flags $execname + + file_on_host delete $execname + + rs-obj [lindex ${src_list} 1] [lindex ${obj_list} 1] "" "" "" "" + rs-obj [lindex ${src_list} 0] [lindex ${obj_list} 0] "" "" "" "" + + gcc-dg-runtest [lindex ${src_list} 0] "" "" + + # FIXME it would be ideal if we could link then execute these tests. + # I was not able to figure out how to specify gc-dg-runtest to link + # against the first object. +} + +proc rs-link-execute { src1 } { + rs-execute-1 $src1 +} + +# Main loop. +foreach src [lsort [find $srcdir/$subdir *_0.rs]] { + # If we're only testing specific files and this isn't one of them, skip it. + if ![runtest_file_p $runtests $src] then { + continue + } + + # To prevent 'runtest_file_p' being tested again (for example, via + # 'gcc-dg-runtest'), with undesirable consequences due to its side effects, + # interpose a dummy: + rename runtest_file_p saved_runtest_file_p + proc runtest_file_p { runtests testcase } { + return 1 + } + rs-link-execute $src + rename runtest_file_p {} + rename saved_runtest_file_p runtest_file_p +} + +set dg-do-what-default ${saved-dg-do-what-default} + +# All done. +dg-finish diff --git a/gcc/testsuite/rust/link/simple_function_0.rs b/gcc/testsuite/rust/link/simple_function_0.rs new file mode 100644 index 00000000000..5bd4926def8 --- /dev/null +++ b/gcc/testsuite/rust/link/simple_function_0.rs @@ -0,0 +1,8 @@ +extern crate simple_function_1; +use simple_function_1::test_func; + +fn main() -> i32 { + let a = test_func(123); + // { dg-bogus "call to extern function" "" { xfail *-*-* } .-1 } + a - 124 +} diff --git a/gcc/testsuite/rust/link/simple_function_1.rs b/gcc/testsuite/rust/link/simple_function_1.rs new file mode 100644 index 00000000000..aaa1fc39367 --- /dev/null +++ b/gcc/testsuite/rust/link/simple_function_1.rs @@ -0,0 +1,3 @@ +pub fn test_func(a: i32) -> i32 { + a + 1 +} diff --git a/gcc/testsuite/rust/link/trait_import_0.rs b/gcc/testsuite/rust/link/trait_import_0.rs new file mode 100644 index 00000000000..ac8c5811d22 --- /dev/null +++ b/gcc/testsuite/rust/link/trait_import_0.rs @@ -0,0 +1,19 @@ +extern crate trait_import_1; +use trait_import_1::Add; + +struct Foo(i32); + +impl Add for Foo { + type Output = Foo; + + fn add(self, other: Foo) -> Foo { + Foo(self.0 + other.0) + } +} + +fn main() -> i32 { + let a; + a = Foo(1) + Foo(2); + + 0 +} diff --git a/gcc/testsuite/rust/link/trait_import_1.rs b/gcc/testsuite/rust/link/trait_import_1.rs new file mode 100644 index 00000000000..fc7f5168ede --- /dev/null +++ b/gcc/testsuite/rust/link/trait_import_1.rs @@ -0,0 +1,6 @@ +#[lang = "add"] +pub trait Add { + type Output; + + fn add(self, rhs: Rhs) -> Self::Output; +} From patchwork Wed Aug 24 11:59:24 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: herron.philip@googlemail.com X-Patchwork-Id: 56987 Return-Path: X-Original-To: patchwork@sourceware.org Delivered-To: patchwork@sourceware.org Received: from server2.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id C09CC384D1BD for ; Wed, 24 Aug 2022 12:03:24 +0000 (GMT) X-Original-To: gcc-patches@gcc.gnu.org Delivered-To: gcc-patches@gcc.gnu.org Received: from mail-wm1-x329.google.com (mail-wm1-x329.google.com [IPv6:2a00:1450:4864:20::329]) by sourceware.org (Postfix) with ESMTPS id 11997384D169; Wed, 24 Aug 2022 12:00:35 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.1 sourceware.org 11997384D169 Authentication-Results: sourceware.org; dmarc=pass (p=quarantine dis=none) header.from=googlemail.com Authentication-Results: sourceware.org; spf=pass smtp.mailfrom=googlemail.com Received: by mail-wm1-x329.google.com with SMTP id ay12so8656480wmb.1; Wed, 24 Aug 2022 05:00:35 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=googlemail.com; s=20210112; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc; bh=4Zx2naMINAeeouJbrJFTlh3rrVAcytOwARVkhQ59FGI=; b=BEpBtm68rbR90pfDAh+M47R+0niFv/ZdhqbGnyCx4ti1Fv+TV+dZObTykhGy9NjXN4 1gP55mOmEKBL8Jw+/LjlM9jsdxnI9+dK/iRrhxtUcDpQEE4xfTubjuzA4JPVxVvyNrfZ jK+B3bxFfGU+pUQAGIoJpdGuUpVEJQheUJPGdUq3xRCxjan4GAlFgvI6PWqxkGahA5bY sCxR+IyuXva9xOnpd0a0Eg1F3F+wjH7gMbfLT8N2ZcWx5FixBdDUxVhWorbJl3wChT3g XQdMeMeVcrOs6eW/OV2dkke5dNwOXnVkKxCS8UoK1SqLjnzp30HbX2le8EOwdOm03h31 W8Hw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc; bh=4Zx2naMINAeeouJbrJFTlh3rrVAcytOwARVkhQ59FGI=; b=JXevuLLYFtlMHPDMzmV5X1fznF/mMguabPqXAqNH+KJE3saLyipOIfHf1P6j0h3d/7 dZ79H4Q1CbwzOvPE6UnSpUXYNWlnLTNDzQn0LE1D9PVDejIMB856R7+HfhNdKj5+eWj6 4IVMu3bT289iCMcvwHnZzagf94DZqYpcmwxPbaOc1JExKQXRe1HzIzn2ujwRh+saAysy uOxVDC/w7J4qpIJATfAgRWzpZIwdR3lkYRNWJPvNPZQcK5vmoW8L7ZcesWCpDnNjy1QE lM2/ekSk6Yi58oJROyzR0erToFxLCO7QBD0JefwUlvBPErIcHnUSae3rzSct4dv40heq WuYw== X-Gm-Message-State: ACgBeo2TLSIXkarHVxAR9HsBh/lqSLe3F6WWLkf7SeuBc7vXHwbV+alf ta39vue27jBp2qwM6ChovqWPLCiTsrQ= X-Google-Smtp-Source: AA6agR6JDCkBIx3SWjnCslTbfC/uDwUm9ISmd1V2iOIF5LX00mzEPkUp7XrAN4SFA1w5o99uTuaSCw== X-Received: by 2002:a05:600c:6025:b0:3a6:ff6:de7e with SMTP id az37-20020a05600c602500b003a60ff6de7emr5034784wmb.173.1661342431790; Wed, 24 Aug 2022 05:00:31 -0700 (PDT) Received: from localhost.localdomain ([86.14.124.218]) by smtp.gmail.com with ESMTPSA id cc19-20020a5d5c13000000b0022571d43d32sm1697676wrb.21.2022.08.24.05.00.30 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 24 Aug 2022 05:00:31 -0700 (PDT) From: herron.philip@googlemail.com X-Google-Original-From: philip.herron@embecosm.com To: gcc-patches@gcc.gnu.org Subject: [PATCH Rust front-end v2 05/37] gccrs: Add general compilation test cases Date: Wed, 24 Aug 2022 12:59:24 +0100 Message-Id: <20220824115956.737931-6-philip.herron@embecosm.com> X-Mailer: git-send-email 2.25.1 In-Reply-To: <20220824115956.737931-1-philip.herron@embecosm.com> References: <20220824115956.737931-1-philip.herron@embecosm.com> MIME-Version: 1.0 X-Spam-Status: No, score=-5.1 required=5.0 tests=BAYES_00, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, DKIM_VALID_EF, FREEMAIL_FROM, RCVD_IN_DNSWL_NONE, SPF_HELO_NONE, SPF_PASS, TXREP, T_SCC_BODY_TEXT_LINE autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on server2.sourceware.org X-BeenThere: gcc-patches@gcc.gnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: Gcc-patches mailing list List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Reply-To: philip.herron@embecosm.com Cc: =?utf-8?q?Marc_Poulhi=C3=A8s?= , Philip Herron , Mark Wielaard , Arthur Cohen , gcc-rust@gcc.gnu.org, Thomas Schwinge Errors-To: gcc-patches-bounces+patchwork=sourceware.org@gcc.gnu.org Sender: "Gcc-patches" From: Philip Herron This suite of tests has two sections compile/*.rs and compile/torture/*.rs. The first section are all dg-compile tests which contain dg-warning or dg-error annotations and some with no annotations to ensure they do create a resulting asm output. The second section is the same but have tests which are ran with the full torture options, as during development the test case may have had an issue with a specific optimization level. Co-authored-by: Arthur Cohen Co-authored-by: Thomas Schwinge Co-authored-by: Mark Wielaard Co-authored-by: Marc Poulhiès --- gcc/testsuite/rust/compile/abi-options1.rs | 7 ++ gcc/testsuite/rust/compile/array3.rs | 4 + .../rust/compile/array_empty_list.rs | 4 + gcc/testsuite/rust/compile/arrays1.rs | 4 + gcc/testsuite/rust/compile/arrays2.rs | 5 + .../rust/compile/attr-mismatch-crate-name.rs | 4 + gcc/testsuite/rust/compile/attr_cold.rs | 12 +++ gcc/testsuite/rust/compile/attr_deprecated.rs | 14 +++ .../rust/compile/attr_deprecated_2.rs | 11 +++ gcc/testsuite/rust/compile/bad-crate-name.rs | 4 + gcc/testsuite/rust/compile/bad=file-name.rs | 7 ++ .../rust/compile/bad_as_bool_char.rs | 18 ++++ .../rust/compile/bad_file_name.txt.rs | 3 + gcc/testsuite/rust/compile/bad_inner_doc.rs | 15 +++ .../rust/compile/bad_pub_enumitems.rs | 47 +++++++++ gcc/testsuite/rust/compile/bad_stmt_enums.rs | 22 +++++ .../rust/compile/bad_toplevel_enums.rs | 19 ++++ gcc/testsuite/rust/compile/bad_tuple_index.rs | 66 +++++++++++++ gcc/testsuite/rust/compile/bad_type1.rs | 3 + gcc/testsuite/rust/compile/bad_type2.rs | 14 +++ gcc/testsuite/rust/compile/break1.rs | 6 ++ gcc/testsuite/rust/compile/break2.rs | 15 +++ .../compile/builtin_macro_compile_error.rs | 13 +++ .../rust/compile/builtin_macro_concat.rs | 17 ++++ .../rust/compile/builtin_macro_env.rs | 20 ++++ .../compile/builtin_macro_include_bytes.rs | 13 +++ .../rust/compile/builtin_macro_include_str.rs | 13 +++ .../rust/compile/builtin_macro_not_found.rs | 4 + gcc/testsuite/rust/compile/bytecharstring.rs | 8 ++ .../rust/compile/canonical_paths1.rs | 25 +++++ gcc/testsuite/rust/compile/cast1.rs | 5 + gcc/testsuite/rust/compile/cfg1.rs | 31 ++++++ gcc/testsuite/rust/compile/cfg2.rs | 13 +++ gcc/testsuite/rust/compile/cfg3.rs | 11 +++ gcc/testsuite/rust/compile/cfg4.rs | 11 +++ gcc/testsuite/rust/compile/cfg5.rs | 11 +++ gcc/testsuite/rust/compile/compile.exp | 35 +++++++ gcc/testsuite/rust/compile/complex-path1.rs | 18 ++++ gcc/testsuite/rust/compile/const-issue1440.rs | 76 +++++++++++++++ gcc/testsuite/rust/compile/const1.rs | 6 ++ gcc/testsuite/rust/compile/const2.rs | 7 ++ gcc/testsuite/rust/compile/const3.rs | 7 ++ .../rust/compile/const_generics_1.rs | 19 ++++ .../rust/compile/const_generics_2.rs | 4 + .../rust/compile/const_generics_3.rs | 26 +++++ .../rust/compile/const_generics_4.rs | 7 ++ .../rust/compile/const_generics_5.rs | 12 +++ .../rust/compile/const_generics_6.rs | 2 + gcc/testsuite/rust/compile/continue1.rs | 10 ++ gcc/testsuite/rust/compile/deadcode_err1.rs | 11 +++ gcc/testsuite/rust/compile/deadcode_err2.rs | 16 +++ .../rust/compile/debug-diagnostics-default.rs | 5 + .../rust/compile/debug-diagnostics-off.rs | 7 ++ .../rust/compile/debug-diagnostics-on.rs | 7 ++ .../compile/doc_isolated_cr_block_comment.rs | 3 + .../doc_isolated_cr_inner_block_comment.rs | 5 + .../doc_isolated_cr_inner_line_comment.rs | 5 + .../compile/doc_isolated_cr_line_comment.rs | 3 + gcc/testsuite/rust/compile/dup_fields.rs | 23 +++++ .../compile/empty_comment_before_match.rs | 7 ++ .../rust/compile/expected_type_args2.rs | 6 ++ .../rust/compile/expected_type_args3.rs | 8 ++ gcc/testsuite/rust/compile/func1.rs | 9 ++ gcc/testsuite/rust/compile/func2.rs | 7 ++ gcc/testsuite/rust/compile/func3.rs | 9 ++ gcc/testsuite/rust/compile/func4.rs | 6 ++ gcc/testsuite/rust/compile/func5.rs | 7 ++ .../rust/compile/generic-default1.rs | 7 ++ gcc/testsuite/rust/compile/generics1.rs | 11 +++ gcc/testsuite/rust/compile/generics10.rs | 12 +++ gcc/testsuite/rust/compile/generics11.rs | 12 +++ gcc/testsuite/rust/compile/generics12.rs | 6 ++ gcc/testsuite/rust/compile/generics13.rs | 1 + gcc/testsuite/rust/compile/generics2.rs | 11 +++ gcc/testsuite/rust/compile/generics3.rs | 10 ++ gcc/testsuite/rust/compile/generics4.rs | 16 +++ gcc/testsuite/rust/compile/generics5.rs | 10 ++ gcc/testsuite/rust/compile/generics6.rs | 31 ++++++ gcc/testsuite/rust/compile/generics7.rs | 26 +++++ gcc/testsuite/rust/compile/generics8.rs | 15 +++ gcc/testsuite/rust/compile/generics9.rs | 10 ++ .../rust/compile/implicit_returns_err1.rs | 12 +++ .../rust/compile/implicit_returns_err2.rs | 10 ++ .../rust/compile/implicit_returns_err3.rs | 9 ++ .../rust/compile/implicit_returns_err4.rs | 10 ++ .../rust/compile/infer-crate-name.rs | 7 ++ gcc/testsuite/rust/compile/inline_1.rs | 16 +++ gcc/testsuite/rust/compile/inline_2.rs | 6 ++ gcc/testsuite/rust/compile/issue-1005.rs | 4 + gcc/testsuite/rust/compile/issue-1019.rs | 19 ++++ gcc/testsuite/rust/compile/issue-1023.rs | 4 + gcc/testsuite/rust/compile/issue-1031.rs | 17 ++++ gcc/testsuite/rust/compile/issue-1034.rs | 16 +++ gcc/testsuite/rust/compile/issue-1089.rs | 6 ++ gcc/testsuite/rust/compile/issue-1128.rs | 6 ++ gcc/testsuite/rust/compile/issue-1129-1.rs | 4 + gcc/testsuite/rust/compile/issue-1129-2.rs | 22 +++++ gcc/testsuite/rust/compile/issue-1130.rs | 47 +++++++++ gcc/testsuite/rust/compile/issue-1131.rs | 4 + gcc/testsuite/rust/compile/issue-1152.rs | 8 ++ gcc/testsuite/rust/compile/issue-1165.rs | 5 + gcc/testsuite/rust/compile/issue-1173.rs | 23 +++++ gcc/testsuite/rust/compile/issue-1226.rs | 6 ++ gcc/testsuite/rust/compile/issue-1234.rs | 4 + gcc/testsuite/rust/compile/issue-1235.rs | 21 ++++ gcc/testsuite/rust/compile/issue-1237.rs | 23 +++++ gcc/testsuite/rust/compile/issue-1251.rs | 14 +++ gcc/testsuite/rust/compile/issue-1271.rs | 5 + gcc/testsuite/rust/compile/issue-1289.rs | 43 +++++++++ gcc/testsuite/rust/compile/issue-1323-1.rs | 18 ++++ gcc/testsuite/rust/compile/issue-1323-2.rs | 16 +++ gcc/testsuite/rust/compile/issue-1383.rs | 8 ++ gcc/testsuite/rust/compile/issue-1393.rs | 13 +++ gcc/testsuite/rust/compile/issue-1447.rs | 28 ++++++ gcc/testsuite/rust/compile/issue-407-2.rs | 21 ++++ gcc/testsuite/rust/compile/issue-407.rs | 9 ++ gcc/testsuite/rust/compile/issue-557.rs | 4 + gcc/testsuite/rust/compile/issue-635-1.rs | 5 + gcc/testsuite/rust/compile/issue-635-2.rs | 5 + gcc/testsuite/rust/compile/lookup_err1.rs | 7 ++ .../rust/compile/macro-issue1053-2.rs | 5 + gcc/testsuite/rust/compile/macro-issue1053.rs | 3 + gcc/testsuite/rust/compile/macro-issue1224.rs | 9 ++ gcc/testsuite/rust/compile/macro-issue1233.rs | 22 +++++ .../rust/compile/macro-issue1395-2.rs | 7 ++ gcc/testsuite/rust/compile/macro-issue1395.rs | 5 + .../rust/compile/macro-issue1400-2.rs | 32 ++++++ gcc/testsuite/rust/compile/macro-issue1400.rs | 33 +++++++ gcc/testsuite/rust/compile/macro1.rs | 3 + gcc/testsuite/rust/compile/macro10.rs | 11 +++ gcc/testsuite/rust/compile/macro11.rs | 11 +++ gcc/testsuite/rust/compile/macro12.rs | 8 ++ gcc/testsuite/rust/compile/macro13.rs | 12 +++ gcc/testsuite/rust/compile/macro14.rs | 10 ++ gcc/testsuite/rust/compile/macro15.rs | 12 +++ gcc/testsuite/rust/compile/macro16.rs | 11 +++ gcc/testsuite/rust/compile/macro17.rs | 10 ++ gcc/testsuite/rust/compile/macro18.rs | 14 +++ gcc/testsuite/rust/compile/macro19.rs | 19 ++++ gcc/testsuite/rust/compile/macro2.rs | 3 + gcc/testsuite/rust/compile/macro20.rs | 16 +++ gcc/testsuite/rust/compile/macro21.rs | 9 ++ gcc/testsuite/rust/compile/macro22.rs | 10 ++ gcc/testsuite/rust/compile/macro23.rs | 25 +++++ gcc/testsuite/rust/compile/macro25.rs | 9 ++ gcc/testsuite/rust/compile/macro26.rs | 10 ++ gcc/testsuite/rust/compile/macro27.rs | 8 ++ gcc/testsuite/rust/compile/macro28.rs | 8 ++ gcc/testsuite/rust/compile/macro29.rs | 8 ++ gcc/testsuite/rust/compile/macro3.rs | 3 + gcc/testsuite/rust/compile/macro30.rs | 8 ++ gcc/testsuite/rust/compile/macro31.rs | 8 ++ gcc/testsuite/rust/compile/macro32.rs | 19 ++++ gcc/testsuite/rust/compile/macro33.rs | 5 + gcc/testsuite/rust/compile/macro34.rs | 3 + gcc/testsuite/rust/compile/macro35.rs | 7 ++ gcc/testsuite/rust/compile/macro36.rs | 3 + gcc/testsuite/rust/compile/macro37.rs | 5 + gcc/testsuite/rust/compile/macro38.rs | 5 + gcc/testsuite/rust/compile/macro39.rs | 5 + gcc/testsuite/rust/compile/macro4.rs | 3 + gcc/testsuite/rust/compile/macro40.rs | 48 +++++++++ gcc/testsuite/rust/compile/macro41.rs | 13 +++ gcc/testsuite/rust/compile/macro42.rs | 32 ++++++ gcc/testsuite/rust/compile/macro5.rs | 3 + gcc/testsuite/rust/compile/macro6.rs | 11 +++ gcc/testsuite/rust/compile/macro7.rs | 13 +++ gcc/testsuite/rust/compile/macro8.rs | 12 +++ gcc/testsuite/rust/compile/macro9.rs | 17 ++++ gcc/testsuite/rust/compile/macro_return.rs | 10 ++ gcc/testsuite/rust/compile/match1.rs | 16 +++ gcc/testsuite/rust/compile/match2.rs | 15 +++ gcc/testsuite/rust/compile/match3.rs | 16 +++ gcc/testsuite/rust/compile/match4.rs | 16 +++ gcc/testsuite/rust/compile/match5.rs | 15 +++ gcc/testsuite/rust/compile/match6.rs | 18 ++++ gcc/testsuite/rust/compile/match7.rs | 12 +++ gcc/testsuite/rust/compile/method1.rs | 13 +++ gcc/testsuite/rust/compile/method2.rs | 16 +++ .../rust/compile/mismatch-crate-name.rs | 4 + .../rust/compile/missing_middle/both_path.rs | 3 + .../compile/missing_middle/explicit.not.rs | 1 + .../rust/compile/missing_middle/inner_path.rs | 3 + .../rust/compile/missing_middle/other.rs | 3 + .../rust/compile/missing_middle/outer_path.rs | 3 + .../rust/compile/missing_middle/sub/mod.rs | 3 + gcc/testsuite/rust/compile/missing_return1.rs | 6 ++ .../rust/compile/mod_missing_middle.rs | 29 ++++++ gcc/testsuite/rust/compile/never_type_err1.rs | 14 +++ gcc/testsuite/rust/compile/privacy1.rs | 11 +++ gcc/testsuite/rust/compile/privacy2.rs | 13 +++ gcc/testsuite/rust/compile/privacy3.rs | 28 ++++++ gcc/testsuite/rust/compile/privacy4.rs | 19 ++++ gcc/testsuite/rust/compile/privacy5.rs | 17 ++++ gcc/testsuite/rust/compile/privacy6.rs | 39 ++++++++ .../rust/compile/pub_restricted_1.rs | 13 +++ .../rust/compile/pub_restricted_2.rs | 18 ++++ .../rust/compile/pub_restricted_3.rs | 11 +++ .../compile/raw_identifiers_bad_keywords.rs | 3 + .../compile/raw_identifiers_underscore.rs | 3 + gcc/testsuite/rust/compile/rawbytestring.rs | Bin 0 -> 3234 bytes gcc/testsuite/rust/compile/redef_error1.rs | 8 ++ gcc/testsuite/rust/compile/redef_error2.rs | 4 + gcc/testsuite/rust/compile/redef_error3.rs | 9 ++ gcc/testsuite/rust/compile/redef_error4.rs | 27 ++++++ gcc/testsuite/rust/compile/redef_error5.rs | 8 ++ gcc/testsuite/rust/compile/redef_error6.rs | 13 +++ gcc/testsuite/rust/compile/reference1.rs | 6 ++ gcc/testsuite/rust/compile/self-path1.rs | 12 +++ gcc/testsuite/rust/compile/self-path2.rs | 21 ++++ gcc/testsuite/rust/compile/shadow1.rs | 7 ++ .../rust/compile/specify-crate-name.rs | 7 ++ gcc/testsuite/rust/compile/static_var1.rs | 5 + .../rust/compile/stmt_with_block_err1.rs | 17 ++++ gcc/testsuite/rust/compile/struct_align1.rs | 19 ++++ gcc/testsuite/rust/compile/struct_align2.rs | 18 ++++ gcc/testsuite/rust/compile/struct_init1.rs | 10 ++ gcc/testsuite/rust/compile/struct_pack1.rs | 19 ++++ gcc/testsuite/rust/compile/struct_pack2.rs | 18 ++++ gcc/testsuite/rust/compile/syntax-only.rs | 6 ++ gcc/testsuite/rust/compile/test_mod.rs | 6 ++ .../torture/all_doc_comment_line_blocks.rs | 45 +++++++++ .../all_doc_comment_line_blocks_crlf.rs | 48 +++++++++ .../torture/arithmetic_expressions1.rs | 30 ++++++ .../compile/torture/array_const_fold_1.rs | 2 + .../compile/torture/array_const_fold_2.rs | 3 + .../rust/compile/torture/array_function.rs | 8 ++ .../rust/compile/torture/array_type_infer.rs | 4 + .../rust/compile/torture/array_zero_length.rs | 4 + gcc/testsuite/rust/compile/torture/arrays1.rs | 9 ++ gcc/testsuite/rust/compile/torture/arrays2.rs | 8 ++ gcc/testsuite/rust/compile/torture/arrays3.rs | 6 ++ gcc/testsuite/rust/compile/torture/arrays4.rs | 6 ++ gcc/testsuite/rust/compile/torture/arrays5.rs | 6 ++ gcc/testsuite/rust/compile/torture/arrays6.rs | 10 ++ .../rust/compile/torture/arrays_index1.rs | 9 ++ .../rust/compile/torture/arrays_index2.rs | 4 + .../rust/compile/torture/arrays_index3.rs | 15 +++ .../rust/compile/torture/as_bool_char.rs | 36 +++++++ .../rust/compile/torture/associated_types1.rs | 12 +++ .../rust/compile/torture/autoderef1.rs | 15 +++ .../rust/compile/torture/block_expr1.rs | 29 ++++++ .../rust/compile/torture/block_expr2.rs | 15 +++ .../rust/compile/torture/block_expr3.rs | 14 +++ .../rust/compile/torture/block_expr4.rs | 8 ++ .../rust/compile/torture/block_expr5.rs | 40 ++++++++ .../compile/torture/block_expr_parser_bug.rs | 5 + gcc/testsuite/rust/compile/torture/bom.rs | 1 + .../rust/compile/torture/bom_comment.rs | 2 + .../rust/compile/torture/bom_shebang.rs | 2 + .../rust/compile/torture/bom_whitespace.rs | 2 + .../rust/compile/torture/bools_eq.rs | 18 ++++ gcc/testsuite/rust/compile/torture/borrow1.rs | 17 ++++ .../rust/compile/torture/borrow_function.rs | 5 + .../rust/compile/torture/break_function.rs | 10 ++ .../rust/compile/torture/byte_char_str.rs | 8 ++ .../rust/compile/torture/byte_str.rs | 4 + gcc/testsuite/rust/compile/torture/cast1.rs | 5 + gcc/testsuite/rust/compile/torture/cast2.rs | 5 + gcc/testsuite/rust/compile/torture/cast3.rs | 6 ++ .../rust/compile/torture/cfg_attr.rs | 7 ++ gcc/testsuite/rust/compile/torture/char1.rs | 4 + .../compile/torture/check-doc-attr-string.rs | 18 ++++ .../rust/compile/torture/coercion1.rs | 11 +++ .../rust/compile/torture/coercion2.rs | 20 ++++ .../rust/compile/torture/comparison_expr1.rs | 38 ++++++++ .../rust/compile/torture/compile.exp | 33 +++++++ .../torture/compound_assignment_expr1.rs | 23 +++++ .../rust/compile/torture/conditional.rs | 11 +++ .../rust/compile/torture/constant1.rs | 9 ++ .../rust/compile/torture/constant2.rs | 6 ++ .../rust/compile/torture/constant3.rs | 10 ++ .../rust/compile/torture/deadcode1.rs | 22 +++++ .../rust/compile/torture/deadcode2.rs | 10 ++ gcc/testsuite/rust/compile/torture/deref1.rs | 6 ++ .../rust/compile/torture/deref_function.rs | 10 ++ .../rust/compile/torture/doc_comment.rs | 16 +++ gcc/testsuite/rust/compile/torture/enum1.rs | 13 +++ .../rust/compile/torture/extern_mod1.rs | 6 ++ .../rust/compile/torture/extern_mod2.rs | 23 +++++ gcc/testsuite/rust/compile/torture/float1.rs | 9 ++ .../rust/compile/torture/float_types.rs | 13 +++ .../rust/compile/torture/forward_decl_1.rs | 11 +++ .../rust/compile/torture/forward_decl_2.rs | 6 ++ .../compile/torture/forward_decl_3-unsafe.rs | 13 +++ .../rust/compile/torture/forward_decl_3.rs | 11 +++ .../rust/compile/torture/forward_decl_4.rs | 9 ++ .../rust/compile/torture/forward_decl_5.rs | 19 ++++ gcc/testsuite/rust/compile/torture/func1.rs | 7 ++ gcc/testsuite/rust/compile/torture/func2.rs | 20 ++++ .../compile/torture/function_reference1.rs | 9 ++ .../compile/torture/function_reference2.rs | 9 ++ .../compile/torture/function_reference3.rs | 20 ++++ .../compile/torture/function_reference4.rs | 9 ++ .../rust/compile/torture/generics1.rs | 51 ++++++++++ .../rust/compile/torture/generics10.rs | 20 ++++ .../rust/compile/torture/generics11.rs | 8 ++ .../rust/compile/torture/generics12.rs | 17 ++++ .../rust/compile/torture/generics13.rs | 41 ++++++++ .../rust/compile/torture/generics14.rs | 20 ++++ .../rust/compile/torture/generics15.rs | 23 +++++ .../rust/compile/torture/generics16.rs | 31 ++++++ .../rust/compile/torture/generics17.rs | 19 ++++ .../rust/compile/torture/generics18.rs | 20 ++++ .../rust/compile/torture/generics19.rs | 12 +++ .../rust/compile/torture/generics2.rs | 45 +++++++++ .../rust/compile/torture/generics20.rs | 12 +++ .../rust/compile/torture/generics21.rs | 13 +++ .../rust/compile/torture/generics22.rs | 13 +++ .../rust/compile/torture/generics23.rs | 6 ++ .../rust/compile/torture/generics24.rs | 34 +++++++ .../rust/compile/torture/generics25.rs | 9 ++ .../rust/compile/torture/generics26.rs | 21 ++++ .../rust/compile/torture/generics27.rs | 16 +++ .../rust/compile/torture/generics28.rs | 18 ++++ .../rust/compile/torture/generics29.rs | 16 +++ .../rust/compile/torture/generics3.rs | 15 +++ .../rust/compile/torture/generics30.rs | 16 +++ .../rust/compile/torture/generics31.rs | 15 +++ .../rust/compile/torture/generics32.rs | 15 +++ .../rust/compile/torture/generics4.rs | 17 ++++ .../rust/compile/torture/generics5.rs | 10 ++ .../rust/compile/torture/generics6.rs | 16 +++ .../rust/compile/torture/generics7.rs | 14 +++ .../rust/compile/torture/generics8.rs | 18 ++++ .../rust/compile/torture/generics9.rs | 25 +++++ .../compile/torture/grouped_expr_function.rs | 6 ++ .../torture/identifier-missing-impl-1.rs | 19 ++++ gcc/testsuite/rust/compile/torture/if.rs | 19 ++++ gcc/testsuite/rust/compile/torture/if_elif.rs | 20 ++++ .../compile/torture/if_elif_else_expr1.rs | 14 +++ gcc/testsuite/rust/compile/torture/if_else.rs | 19 ++++ .../rust/compile/torture/ifunaryexpr.rs | 22 +++++ .../rust/compile/torture/impl_block1.rs | 23 +++++ .../rust/compile/torture/impl_block2.rs | 28 ++++++ .../rust/compile/torture/impl_block3.rs | 36 +++++++ .../rust/compile/torture/impl_block_unused.rs | 17 ++++ .../rust/compile/torture/implicit_returns1.rs | 73 ++++++++++++++ .../rust/compile/torture/infer_type1.rs | 4 + .../rust/compile/torture/inner_attributes.rs | 3 + .../compile/torture/integer_inference_var1.rs | 6 ++ .../compile/torture/integer_inference_var2.rs | 6 ++ .../compile/torture/integer_inference_var3.rs | 11 +++ .../compile/torture/integer_inference_var4.rs | 4 + .../compile/torture/integer_inference_var5.rs | 25 +++++ .../rust/compile/torture/integer_types.rs | 27 ++++++ .../rust/compile/torture/intrinsics-1.rs | 22 +++++ .../rust/compile/torture/intrinsics-2.rs | 22 +++++ .../torture/isolated_cr_block_comment.rs | 2 + .../torture/isolated_cr_line_comment.rs | 2 + .../rust/compile/torture/issue-1024.rs | 11 +++ .../rust/compile/torture/issue-1075.rs | 42 ++++++++ .../rust/compile/torture/issue-1432.rs | 77 +++++++++++++++ .../rust/compile/torture/issue-1434.rs | 53 ++++++++++ .../rust/compile/torture/issue-368.rs | 9 ++ .../rust/compile/torture/issue-808.rs | 20 ++++ .../rust/compile/torture/issue-862.rs | 74 ++++++++++++++ .../rust/compile/torture/issue-893-2.rs | 35 +++++++ .../rust/compile/torture/issue-893.rs | 11 +++ .../torture/lazybooleanexpr_function.rs | 14 +++ .../rust/compile/torture/lifetime1.rs | 7 ++ .../rust/compile/torture/literals1.rs | 11 +++ gcc/testsuite/rust/compile/torture/loop1.rs | 10 ++ gcc/testsuite/rust/compile/torture/loop2.rs | 14 +++ gcc/testsuite/rust/compile/torture/loop3.rs | 14 +++ gcc/testsuite/rust/compile/torture/loop4.rs | 7 ++ gcc/testsuite/rust/compile/torture/loop5.rs | 14 +++ gcc/testsuite/rust/compile/torture/loop6.rs | 11 +++ gcc/testsuite/rust/compile/torture/loop7.rs | 13 +++ .../rust/compile/torture/macro-issue1403.rs | 23 +++++ .../rust/compile/torture/macro-issue1426.rs | 32 ++++++ .../rust/compile/torture/macro_as_expr.rs | 14 +++ gcc/testsuite/rust/compile/torture/match1.rs | 16 +++ .../rust/compile/torture/methods1.rs | 41 ++++++++ .../rust/compile/torture/methods2.rs | 43 +++++++++ .../rust/compile/torture/methods3.rs | 44 +++++++++ .../rust/compile/torture/mod-nameresolve.rs | 5 + gcc/testsuite/rust/compile/torture/mod1.rs | 11 +++ gcc/testsuite/rust/compile/torture/mod2.rs | 13 +++ gcc/testsuite/rust/compile/torture/mod3.rs | 22 +++++ .../rust/compile/torture/modules/mod.rs | 3 + .../compile/torture/modules/valid_path.rs | 1 + .../rust/compile/torture/must_use1.rs | 16 +++ .../rust/compile/torture/must_use2.rs | 16 +++ .../rust/compile/torture/name_resolve1.rs | 23 +++++ .../rust/compile/torture/negation_function.rs | 7 ++ .../rust/compile/torture/nested_fn1.rs | 10 ++ .../rust/compile/torture/nested_fn2.rs | 11 +++ .../rust/compile/torture/nested_struct1.rs | 20 ++++ .../rust/compile/torture/never_type1.rs | 22 +++++ .../rust/compile/torture/not_shebang.rs | 3 + .../torture/not_shebang_block_comment.rs | 1 + .../compile/torture/not_shebang_comment.rs | 3 + .../torture/not_shebang_multiline_comment.rs | 7 ++ .../compile/torture/not_shebang_spaces.rs | 6 ++ .../rust/compile/torture/parameter_usage1.rs | 8 ++ gcc/testsuite/rust/compile/torture/parens1.rs | 5 + .../rust/compile/torture/pointer1.rs | 9 ++ .../rust/compile/torture/primconsts.rs | 72 ++++++++++++++ .../rust/compile/torture/prims_struct_eq.rs | 91 ++++++++++++++++++ .../rust/compile/torture/range-lang-item1.rs | 32 ++++++ .../rust/compile/torture/raw_identifiers.rs | 3 + .../torture/raw_identifiers_keywords.rs | 3 + .../rust/compile/torture/recursive_fn1.rs | 12 +++ .../rust/compile/torture/return_function.rs | 5 + .../rust/compile/torture/scoping1.rs | 11 +++ .../rust/compile/torture/self_type1.rs | 12 +++ gcc/testsuite/rust/compile/torture/shadow1.rs | 6 ++ gcc/testsuite/rust/compile/torture/shadow2.rs | 5 + gcc/testsuite/rust/compile/torture/shebang.rs | 3 + .../rust/compile/torture/shebang_plus_attr.rs | 3 + .../compile/torture/shebang_plus_attr2.rs | 3 + .../rust/compile/torture/static_function.rs | 8 ++ .../rust/compile/torture/static_var1.rs | 6 ++ .../rust/compile/torture/stmt_with_block1.rs | 13 +++ gcc/testsuite/rust/compile/torture/str1.rs | 7 ++ .../rust/compile/torture/struct_access1.rs | 12 +++ .../compile/torture/struct_base_init_1.rs | 13 +++ .../rust/compile/torture/struct_decl.rs | 14 +++ .../rust/compile/torture/struct_init.rs | 11 +++ .../rust/compile/torture/struct_init_10.rs | 9 ++ .../rust/compile/torture/struct_init_11.rs | 34 +++++++ .../rust/compile/torture/struct_init_2.rs | 6 ++ .../rust/compile/torture/struct_init_3.rs | 13 +++ .../rust/compile/torture/struct_init_4.rs | 13 +++ .../rust/compile/torture/struct_init_5.rs | 10 ++ .../rust/compile/torture/struct_init_6.rs | 11 +++ .../rust/compile/torture/struct_init_7.rs | 11 +++ .../rust/compile/torture/struct_init_8.rs | 7 ++ .../rust/compile/torture/struct_init_9.rs | 6 ++ .../rust/compile/torture/top_attr.rs | 5 + gcc/testsuite/rust/compile/torture/traits1.rs | 16 +++ .../rust/compile/torture/traits10.rs | 30 ++++++ .../rust/compile/torture/traits11.rs | 31 ++++++ .../rust/compile/torture/traits12.rs | 29 ++++++ .../rust/compile/torture/traits13.rs | 17 ++++ .../rust/compile/torture/traits14.rs | 23 +++++ .../rust/compile/torture/traits15.rs | 23 +++++ .../rust/compile/torture/traits16.rs | 20 ++++ .../rust/compile/torture/traits17.rs | 23 +++++ .../rust/compile/torture/traits18.rs | 5 + .../rust/compile/torture/traits19.rs | 33 +++++++ gcc/testsuite/rust/compile/torture/traits2.rs | 16 +++ gcc/testsuite/rust/compile/torture/traits3.rs | 15 +++ gcc/testsuite/rust/compile/torture/traits4.rs | 21 ++++ gcc/testsuite/rust/compile/torture/traits5.rs | 21 ++++ gcc/testsuite/rust/compile/torture/traits6.rs | 20 ++++ gcc/testsuite/rust/compile/torture/traits7.rs | 19 ++++ gcc/testsuite/rust/compile/torture/traits8.rs | 21 ++++ gcc/testsuite/rust/compile/torture/traits9.rs | 27 ++++++ .../compile/torture/transmute-size-check-1.rs | 11 +++ .../rust/compile/torture/transmute1.rs | 11 +++ gcc/testsuite/rust/compile/torture/tuple1.rs | 6 ++ gcc/testsuite/rust/compile/torture/tuple2.rs | 5 + gcc/testsuite/rust/compile/torture/tuple3.rs | 9 ++ .../compile/torture/tuple_enum_variants.rs | 23 +++++ .../compile/torture/tuple_field_access.rs | 6 ++ .../rust/compile/torture/tuple_function.rs | 6 ++ .../rust/compile/torture/tuple_index.rs | 32 ++++++ .../rust/compile/torture/tuple_struct1.rs | 6 ++ .../rust/compile/torture/tuple_struct2.rs | 11 +++ .../rust/compile/torture/tuple_struct_unit.rs | 11 +++ .../compile/torture/tuple_struct_unused.rs | 4 + .../rust/compile/torture/type-alias1.rs | 6 ++ .../rust/compile/torture/type-alias2.rs | 8 ++ .../rust/compile/torture/type_infer1.rs | 24 +++++ .../rust/compile/torture/type_infer2.rs | 9 ++ .../rust/compile/torture/type_infer3.rs | 14 +++ .../rust/compile/torture/type_infer4.rs | 11 +++ .../rust/compile/torture/type_infer5.rs | 13 +++ .../rust/compile/torture/type_infer6.rs | 14 +++ .../rust/compile/torture/unary_operators.rs | 8 ++ .../rust/compile/torture/undended-string-1.rs | 5 + .../rust/compile/torture/undended-string-2.rs | 5 + .../rust/compile/torture/underscore_id.rs | 4 + gcc/testsuite/rust/compile/torture/union.rs | 32 ++++++ .../rust/compile/torture/union_union.rs | 27 ++++++ .../rust/compile/torture/unit_type1.rs | 7 ++ .../rust/compile/torture/unit_type2.rs | 8 ++ .../rust/compile/torture/unit_type3.rs | 6 ++ .../rust/compile/torture/unit_type4.rs | 5 + .../rust/compile/torture/unit_type5.rs | 8 ++ gcc/testsuite/rust/compile/torture/unsafe1.rs | 12 +++ gcc/testsuite/rust/compile/torture/unsafe2.rs | 4 + gcc/testsuite/rust/compile/torture/unsafe3.rs | 9 ++ gcc/testsuite/rust/compile/torture/unsafe4.rs | 12 +++ gcc/testsuite/rust/compile/torture/unused.rs | 17 ++++ gcc/testsuite/rust/compile/torture/unused1.rs | 15 +++ .../rust/compile/torture/unused_struct.rs | 7 ++ .../compile/torture/unused_struct_field.rs | 9 ++ gcc/testsuite/rust/compile/torture/usize1.rs | 6 ++ .../torture/very-broken-attr-string.rs | 3 + .../rust/compile/torture/while_function.rs | 10 ++ gcc/testsuite/rust/compile/traits1.rs | 13 +++ gcc/testsuite/rust/compile/traits10.rs | 15 +++ gcc/testsuite/rust/compile/traits11.rs | 19 ++++ gcc/testsuite/rust/compile/traits12.rs | 20 ++++ gcc/testsuite/rust/compile/traits2.rs | 14 +++ gcc/testsuite/rust/compile/traits3.rs | 22 +++++ gcc/testsuite/rust/compile/traits4.rs | 16 +++ gcc/testsuite/rust/compile/traits5.rs | 9 ++ gcc/testsuite/rust/compile/traits6.rs | 15 +++ gcc/testsuite/rust/compile/traits7.rs | 24 +++++ gcc/testsuite/rust/compile/traits8.rs | 35 +++++++ gcc/testsuite/rust/compile/traits9.rs | 13 +++ gcc/testsuite/rust/compile/tuple1.rs | 5 + gcc/testsuite/rust/compile/tuple_struct1.rs | 8 ++ gcc/testsuite/rust/compile/tuple_struct2.rs | 5 + gcc/testsuite/rust/compile/tuple_struct3.rs | 6 ++ gcc/testsuite/rust/compile/type-alias1.rs | 6 ++ gcc/testsuite/rust/compile/type-bindings1.rs | 10 ++ gcc/testsuite/rust/compile/unary_negation.rs | 9 ++ gcc/testsuite/rust/compile/unary_not.rs | 9 ++ .../rust/compile/unconstrained_type_param.rs | 12 +++ gcc/testsuite/rust/compile/unicode_escape.rs | 60 ++++++++++++ gcc/testsuite/rust/compile/unsafe1.rs | 14 +++ gcc/testsuite/rust/compile/unsafe10.rs | 12 +++ gcc/testsuite/rust/compile/unsafe2.rs | 16 +++ gcc/testsuite/rust/compile/unsafe3.rs | 10 ++ gcc/testsuite/rust/compile/unsafe4.rs | 29 ++++++ gcc/testsuite/rust/compile/unsafe5.rs | 4 + gcc/testsuite/rust/compile/unsafe6.rs | 14 +++ gcc/testsuite/rust/compile/unsafe7.rs | 9 ++ gcc/testsuite/rust/compile/unsafe8.rs | 14 +++ gcc/testsuite/rust/compile/unsafe9.rs | 10 ++ .../rust/compile/unterminated_c_comment.rs | 2 + gcc/testsuite/rust/compile/use_1.rs | 16 +++ gcc/testsuite/rust/compile/usize1.rs | 6 ++ .../rust/compile/xfail/lifetime_param.rs | 11 +++ .../rust/compile/xfail/struct_field_vis.rs | 15 +++ gcc/testsuite/rust/compile/xfail/xfail.exp | 63 ++++++++++++ 531 files changed, 7556 insertions(+) create mode 100644 gcc/testsuite/rust/compile/abi-options1.rs create mode 100644 gcc/testsuite/rust/compile/array3.rs create mode 100644 gcc/testsuite/rust/compile/array_empty_list.rs create mode 100644 gcc/testsuite/rust/compile/arrays1.rs create mode 100644 gcc/testsuite/rust/compile/arrays2.rs create mode 100644 gcc/testsuite/rust/compile/attr-mismatch-crate-name.rs create mode 100644 gcc/testsuite/rust/compile/attr_cold.rs create mode 100644 gcc/testsuite/rust/compile/attr_deprecated.rs create mode 100644 gcc/testsuite/rust/compile/attr_deprecated_2.rs create mode 100644 gcc/testsuite/rust/compile/bad-crate-name.rs create mode 100644 gcc/testsuite/rust/compile/bad=file-name.rs create mode 100644 gcc/testsuite/rust/compile/bad_as_bool_char.rs create mode 100644 gcc/testsuite/rust/compile/bad_file_name.txt.rs create mode 100644 gcc/testsuite/rust/compile/bad_inner_doc.rs create mode 100644 gcc/testsuite/rust/compile/bad_pub_enumitems.rs create mode 100644 gcc/testsuite/rust/compile/bad_stmt_enums.rs create mode 100644 gcc/testsuite/rust/compile/bad_toplevel_enums.rs create mode 100644 gcc/testsuite/rust/compile/bad_tuple_index.rs create mode 100644 gcc/testsuite/rust/compile/bad_type1.rs create mode 100644 gcc/testsuite/rust/compile/bad_type2.rs create mode 100644 gcc/testsuite/rust/compile/break1.rs create mode 100644 gcc/testsuite/rust/compile/break2.rs create mode 100644 gcc/testsuite/rust/compile/builtin_macro_compile_error.rs create mode 100644 gcc/testsuite/rust/compile/builtin_macro_concat.rs create mode 100644 gcc/testsuite/rust/compile/builtin_macro_env.rs create mode 100644 gcc/testsuite/rust/compile/builtin_macro_include_bytes.rs create mode 100644 gcc/testsuite/rust/compile/builtin_macro_include_str.rs create mode 100644 gcc/testsuite/rust/compile/builtin_macro_not_found.rs create mode 100644 gcc/testsuite/rust/compile/bytecharstring.rs create mode 100644 gcc/testsuite/rust/compile/canonical_paths1.rs create mode 100644 gcc/testsuite/rust/compile/cast1.rs create mode 100644 gcc/testsuite/rust/compile/cfg1.rs create mode 100644 gcc/testsuite/rust/compile/cfg2.rs create mode 100644 gcc/testsuite/rust/compile/cfg3.rs create mode 100644 gcc/testsuite/rust/compile/cfg4.rs create mode 100644 gcc/testsuite/rust/compile/cfg5.rs create mode 100644 gcc/testsuite/rust/compile/compile.exp create mode 100644 gcc/testsuite/rust/compile/complex-path1.rs create mode 100644 gcc/testsuite/rust/compile/const-issue1440.rs create mode 100644 gcc/testsuite/rust/compile/const1.rs create mode 100644 gcc/testsuite/rust/compile/const2.rs create mode 100644 gcc/testsuite/rust/compile/const3.rs create mode 100644 gcc/testsuite/rust/compile/const_generics_1.rs create mode 100644 gcc/testsuite/rust/compile/const_generics_2.rs create mode 100644 gcc/testsuite/rust/compile/const_generics_3.rs create mode 100644 gcc/testsuite/rust/compile/const_generics_4.rs create mode 100644 gcc/testsuite/rust/compile/const_generics_5.rs create mode 100644 gcc/testsuite/rust/compile/const_generics_6.rs create mode 100644 gcc/testsuite/rust/compile/continue1.rs create mode 100644 gcc/testsuite/rust/compile/deadcode_err1.rs create mode 100644 gcc/testsuite/rust/compile/deadcode_err2.rs create mode 100644 gcc/testsuite/rust/compile/debug-diagnostics-default.rs create mode 100644 gcc/testsuite/rust/compile/debug-diagnostics-off.rs create mode 100644 gcc/testsuite/rust/compile/debug-diagnostics-on.rs create mode 100644 gcc/testsuite/rust/compile/doc_isolated_cr_block_comment.rs create mode 100644 gcc/testsuite/rust/compile/doc_isolated_cr_inner_block_comment.rs create mode 100644 gcc/testsuite/rust/compile/doc_isolated_cr_inner_line_comment.rs create mode 100644 gcc/testsuite/rust/compile/doc_isolated_cr_line_comment.rs create mode 100644 gcc/testsuite/rust/compile/dup_fields.rs create mode 100644 gcc/testsuite/rust/compile/empty_comment_before_match.rs create mode 100644 gcc/testsuite/rust/compile/expected_type_args2.rs create mode 100644 gcc/testsuite/rust/compile/expected_type_args3.rs create mode 100644 gcc/testsuite/rust/compile/func1.rs create mode 100644 gcc/testsuite/rust/compile/func2.rs create mode 100644 gcc/testsuite/rust/compile/func3.rs create mode 100644 gcc/testsuite/rust/compile/func4.rs create mode 100644 gcc/testsuite/rust/compile/func5.rs create mode 100644 gcc/testsuite/rust/compile/generic-default1.rs create mode 100644 gcc/testsuite/rust/compile/generics1.rs create mode 100644 gcc/testsuite/rust/compile/generics10.rs create mode 100644 gcc/testsuite/rust/compile/generics11.rs create mode 100644 gcc/testsuite/rust/compile/generics12.rs create mode 100644 gcc/testsuite/rust/compile/generics13.rs create mode 100644 gcc/testsuite/rust/compile/generics2.rs create mode 100644 gcc/testsuite/rust/compile/generics3.rs create mode 100644 gcc/testsuite/rust/compile/generics4.rs create mode 100644 gcc/testsuite/rust/compile/generics5.rs create mode 100644 gcc/testsuite/rust/compile/generics6.rs create mode 100644 gcc/testsuite/rust/compile/generics7.rs create mode 100644 gcc/testsuite/rust/compile/generics8.rs create mode 100644 gcc/testsuite/rust/compile/generics9.rs create mode 100644 gcc/testsuite/rust/compile/implicit_returns_err1.rs create mode 100644 gcc/testsuite/rust/compile/implicit_returns_err2.rs create mode 100644 gcc/testsuite/rust/compile/implicit_returns_err3.rs create mode 100644 gcc/testsuite/rust/compile/implicit_returns_err4.rs create mode 100644 gcc/testsuite/rust/compile/infer-crate-name.rs create mode 100644 gcc/testsuite/rust/compile/inline_1.rs create mode 100644 gcc/testsuite/rust/compile/inline_2.rs create mode 100644 gcc/testsuite/rust/compile/issue-1005.rs create mode 100644 gcc/testsuite/rust/compile/issue-1019.rs create mode 100644 gcc/testsuite/rust/compile/issue-1023.rs create mode 100644 gcc/testsuite/rust/compile/issue-1031.rs create mode 100644 gcc/testsuite/rust/compile/issue-1034.rs create mode 100644 gcc/testsuite/rust/compile/issue-1089.rs create mode 100644 gcc/testsuite/rust/compile/issue-1128.rs create mode 100644 gcc/testsuite/rust/compile/issue-1129-1.rs create mode 100644 gcc/testsuite/rust/compile/issue-1129-2.rs create mode 100644 gcc/testsuite/rust/compile/issue-1130.rs create mode 100644 gcc/testsuite/rust/compile/issue-1131.rs create mode 100644 gcc/testsuite/rust/compile/issue-1152.rs create mode 100644 gcc/testsuite/rust/compile/issue-1165.rs create mode 100644 gcc/testsuite/rust/compile/issue-1173.rs create mode 100644 gcc/testsuite/rust/compile/issue-1226.rs create mode 100644 gcc/testsuite/rust/compile/issue-1234.rs create mode 100644 gcc/testsuite/rust/compile/issue-1235.rs create mode 100644 gcc/testsuite/rust/compile/issue-1237.rs create mode 100644 gcc/testsuite/rust/compile/issue-1251.rs create mode 100644 gcc/testsuite/rust/compile/issue-1271.rs create mode 100644 gcc/testsuite/rust/compile/issue-1289.rs create mode 100644 gcc/testsuite/rust/compile/issue-1323-1.rs create mode 100644 gcc/testsuite/rust/compile/issue-1323-2.rs create mode 100644 gcc/testsuite/rust/compile/issue-1383.rs create mode 100644 gcc/testsuite/rust/compile/issue-1393.rs create mode 100644 gcc/testsuite/rust/compile/issue-1447.rs create mode 100644 gcc/testsuite/rust/compile/issue-407-2.rs create mode 100644 gcc/testsuite/rust/compile/issue-407.rs create mode 100644 gcc/testsuite/rust/compile/issue-557.rs create mode 100644 gcc/testsuite/rust/compile/issue-635-1.rs create mode 100644 gcc/testsuite/rust/compile/issue-635-2.rs create mode 100644 gcc/testsuite/rust/compile/lookup_err1.rs create mode 100644 gcc/testsuite/rust/compile/macro-issue1053-2.rs create mode 100644 gcc/testsuite/rust/compile/macro-issue1053.rs create mode 100644 gcc/testsuite/rust/compile/macro-issue1224.rs create mode 100644 gcc/testsuite/rust/compile/macro-issue1233.rs create mode 100644 gcc/testsuite/rust/compile/macro-issue1395-2.rs create mode 100644 gcc/testsuite/rust/compile/macro-issue1395.rs create mode 100644 gcc/testsuite/rust/compile/macro-issue1400-2.rs create mode 100644 gcc/testsuite/rust/compile/macro-issue1400.rs create mode 100644 gcc/testsuite/rust/compile/macro1.rs create mode 100644 gcc/testsuite/rust/compile/macro10.rs create mode 100644 gcc/testsuite/rust/compile/macro11.rs create mode 100644 gcc/testsuite/rust/compile/macro12.rs create mode 100644 gcc/testsuite/rust/compile/macro13.rs create mode 100644 gcc/testsuite/rust/compile/macro14.rs create mode 100644 gcc/testsuite/rust/compile/macro15.rs create mode 100644 gcc/testsuite/rust/compile/macro16.rs create mode 100644 gcc/testsuite/rust/compile/macro17.rs create mode 100644 gcc/testsuite/rust/compile/macro18.rs create mode 100644 gcc/testsuite/rust/compile/macro19.rs create mode 100644 gcc/testsuite/rust/compile/macro2.rs create mode 100644 gcc/testsuite/rust/compile/macro20.rs create mode 100644 gcc/testsuite/rust/compile/macro21.rs create mode 100644 gcc/testsuite/rust/compile/macro22.rs create mode 100644 gcc/testsuite/rust/compile/macro23.rs create mode 100644 gcc/testsuite/rust/compile/macro25.rs create mode 100644 gcc/testsuite/rust/compile/macro26.rs create mode 100644 gcc/testsuite/rust/compile/macro27.rs create mode 100644 gcc/testsuite/rust/compile/macro28.rs create mode 100644 gcc/testsuite/rust/compile/macro29.rs create mode 100644 gcc/testsuite/rust/compile/macro3.rs create mode 100644 gcc/testsuite/rust/compile/macro30.rs create mode 100644 gcc/testsuite/rust/compile/macro31.rs create mode 100644 gcc/testsuite/rust/compile/macro32.rs create mode 100644 gcc/testsuite/rust/compile/macro33.rs create mode 100644 gcc/testsuite/rust/compile/macro34.rs create mode 100644 gcc/testsuite/rust/compile/macro35.rs create mode 100644 gcc/testsuite/rust/compile/macro36.rs create mode 100644 gcc/testsuite/rust/compile/macro37.rs create mode 100644 gcc/testsuite/rust/compile/macro38.rs create mode 100644 gcc/testsuite/rust/compile/macro39.rs create mode 100644 gcc/testsuite/rust/compile/macro4.rs create mode 100644 gcc/testsuite/rust/compile/macro40.rs create mode 100644 gcc/testsuite/rust/compile/macro41.rs create mode 100644 gcc/testsuite/rust/compile/macro42.rs create mode 100644 gcc/testsuite/rust/compile/macro5.rs create mode 100644 gcc/testsuite/rust/compile/macro6.rs create mode 100644 gcc/testsuite/rust/compile/macro7.rs create mode 100644 gcc/testsuite/rust/compile/macro8.rs create mode 100644 gcc/testsuite/rust/compile/macro9.rs create mode 100644 gcc/testsuite/rust/compile/macro_return.rs create mode 100644 gcc/testsuite/rust/compile/match1.rs create mode 100644 gcc/testsuite/rust/compile/match2.rs create mode 100644 gcc/testsuite/rust/compile/match3.rs create mode 100644 gcc/testsuite/rust/compile/match4.rs create mode 100644 gcc/testsuite/rust/compile/match5.rs create mode 100644 gcc/testsuite/rust/compile/match6.rs create mode 100644 gcc/testsuite/rust/compile/match7.rs create mode 100644 gcc/testsuite/rust/compile/method1.rs create mode 100644 gcc/testsuite/rust/compile/method2.rs create mode 100644 gcc/testsuite/rust/compile/mismatch-crate-name.rs create mode 100644 gcc/testsuite/rust/compile/missing_middle/both_path.rs create mode 100644 gcc/testsuite/rust/compile/missing_middle/explicit.not.rs create mode 100644 gcc/testsuite/rust/compile/missing_middle/inner_path.rs create mode 100644 gcc/testsuite/rust/compile/missing_middle/other.rs create mode 100644 gcc/testsuite/rust/compile/missing_middle/outer_path.rs create mode 100644 gcc/testsuite/rust/compile/missing_middle/sub/mod.rs create mode 100644 gcc/testsuite/rust/compile/missing_return1.rs create mode 100644 gcc/testsuite/rust/compile/mod_missing_middle.rs create mode 100644 gcc/testsuite/rust/compile/never_type_err1.rs create mode 100644 gcc/testsuite/rust/compile/privacy1.rs create mode 100644 gcc/testsuite/rust/compile/privacy2.rs create mode 100644 gcc/testsuite/rust/compile/privacy3.rs create mode 100644 gcc/testsuite/rust/compile/privacy4.rs create mode 100644 gcc/testsuite/rust/compile/privacy5.rs create mode 100644 gcc/testsuite/rust/compile/privacy6.rs create mode 100644 gcc/testsuite/rust/compile/pub_restricted_1.rs create mode 100644 gcc/testsuite/rust/compile/pub_restricted_2.rs create mode 100644 gcc/testsuite/rust/compile/pub_restricted_3.rs create mode 100644 gcc/testsuite/rust/compile/raw_identifiers_bad_keywords.rs create mode 100644 gcc/testsuite/rust/compile/raw_identifiers_underscore.rs create mode 100644 gcc/testsuite/rust/compile/rawbytestring.rs create mode 100644 gcc/testsuite/rust/compile/redef_error1.rs create mode 100644 gcc/testsuite/rust/compile/redef_error2.rs create mode 100644 gcc/testsuite/rust/compile/redef_error3.rs create mode 100644 gcc/testsuite/rust/compile/redef_error4.rs create mode 100644 gcc/testsuite/rust/compile/redef_error5.rs create mode 100644 gcc/testsuite/rust/compile/redef_error6.rs create mode 100644 gcc/testsuite/rust/compile/reference1.rs create mode 100644 gcc/testsuite/rust/compile/self-path1.rs create mode 100644 gcc/testsuite/rust/compile/self-path2.rs create mode 100644 gcc/testsuite/rust/compile/shadow1.rs create mode 100644 gcc/testsuite/rust/compile/specify-crate-name.rs create mode 100644 gcc/testsuite/rust/compile/static_var1.rs create mode 100644 gcc/testsuite/rust/compile/stmt_with_block_err1.rs create mode 100644 gcc/testsuite/rust/compile/struct_align1.rs create mode 100644 gcc/testsuite/rust/compile/struct_align2.rs create mode 100644 gcc/testsuite/rust/compile/struct_init1.rs create mode 100644 gcc/testsuite/rust/compile/struct_pack1.rs create mode 100644 gcc/testsuite/rust/compile/struct_pack2.rs create mode 100644 gcc/testsuite/rust/compile/syntax-only.rs create mode 100644 gcc/testsuite/rust/compile/test_mod.rs create mode 100644 gcc/testsuite/rust/compile/torture/all_doc_comment_line_blocks.rs create mode 100644 gcc/testsuite/rust/compile/torture/all_doc_comment_line_blocks_crlf.rs create mode 100644 gcc/testsuite/rust/compile/torture/arithmetic_expressions1.rs create mode 100644 gcc/testsuite/rust/compile/torture/array_const_fold_1.rs create mode 100644 gcc/testsuite/rust/compile/torture/array_const_fold_2.rs create mode 100644 gcc/testsuite/rust/compile/torture/array_function.rs create mode 100644 gcc/testsuite/rust/compile/torture/array_type_infer.rs create mode 100644 gcc/testsuite/rust/compile/torture/array_zero_length.rs create mode 100644 gcc/testsuite/rust/compile/torture/arrays1.rs create mode 100644 gcc/testsuite/rust/compile/torture/arrays2.rs create mode 100644 gcc/testsuite/rust/compile/torture/arrays3.rs create mode 100644 gcc/testsuite/rust/compile/torture/arrays4.rs create mode 100644 gcc/testsuite/rust/compile/torture/arrays5.rs create mode 100644 gcc/testsuite/rust/compile/torture/arrays6.rs create mode 100644 gcc/testsuite/rust/compile/torture/arrays_index1.rs create mode 100644 gcc/testsuite/rust/compile/torture/arrays_index2.rs create mode 100644 gcc/testsuite/rust/compile/torture/arrays_index3.rs create mode 100644 gcc/testsuite/rust/compile/torture/as_bool_char.rs create mode 100644 gcc/testsuite/rust/compile/torture/associated_types1.rs create mode 100644 gcc/testsuite/rust/compile/torture/autoderef1.rs create mode 100644 gcc/testsuite/rust/compile/torture/block_expr1.rs create mode 100644 gcc/testsuite/rust/compile/torture/block_expr2.rs create mode 100644 gcc/testsuite/rust/compile/torture/block_expr3.rs create mode 100644 gcc/testsuite/rust/compile/torture/block_expr4.rs create mode 100644 gcc/testsuite/rust/compile/torture/block_expr5.rs create mode 100644 gcc/testsuite/rust/compile/torture/block_expr_parser_bug.rs create mode 100644 gcc/testsuite/rust/compile/torture/bom.rs create mode 100644 gcc/testsuite/rust/compile/torture/bom_comment.rs create mode 100644 gcc/testsuite/rust/compile/torture/bom_shebang.rs create mode 100644 gcc/testsuite/rust/compile/torture/bom_whitespace.rs create mode 100644 gcc/testsuite/rust/compile/torture/bools_eq.rs create mode 100644 gcc/testsuite/rust/compile/torture/borrow1.rs create mode 100644 gcc/testsuite/rust/compile/torture/borrow_function.rs create mode 100644 gcc/testsuite/rust/compile/torture/break_function.rs create mode 100644 gcc/testsuite/rust/compile/torture/byte_char_str.rs create mode 100644 gcc/testsuite/rust/compile/torture/byte_str.rs create mode 100644 gcc/testsuite/rust/compile/torture/cast1.rs create mode 100644 gcc/testsuite/rust/compile/torture/cast2.rs create mode 100644 gcc/testsuite/rust/compile/torture/cast3.rs create mode 100644 gcc/testsuite/rust/compile/torture/cfg_attr.rs create mode 100644 gcc/testsuite/rust/compile/torture/char1.rs create mode 100644 gcc/testsuite/rust/compile/torture/check-doc-attr-string.rs create mode 100644 gcc/testsuite/rust/compile/torture/coercion1.rs create mode 100644 gcc/testsuite/rust/compile/torture/coercion2.rs create mode 100644 gcc/testsuite/rust/compile/torture/comparison_expr1.rs create mode 100644 gcc/testsuite/rust/compile/torture/compile.exp create mode 100644 gcc/testsuite/rust/compile/torture/compound_assignment_expr1.rs create mode 100644 gcc/testsuite/rust/compile/torture/conditional.rs create mode 100644 gcc/testsuite/rust/compile/torture/constant1.rs create mode 100644 gcc/testsuite/rust/compile/torture/constant2.rs create mode 100644 gcc/testsuite/rust/compile/torture/constant3.rs create mode 100644 gcc/testsuite/rust/compile/torture/deadcode1.rs create mode 100644 gcc/testsuite/rust/compile/torture/deadcode2.rs create mode 100644 gcc/testsuite/rust/compile/torture/deref1.rs create mode 100644 gcc/testsuite/rust/compile/torture/deref_function.rs create mode 100644 gcc/testsuite/rust/compile/torture/doc_comment.rs create mode 100644 gcc/testsuite/rust/compile/torture/enum1.rs create mode 100644 gcc/testsuite/rust/compile/torture/extern_mod1.rs create mode 100644 gcc/testsuite/rust/compile/torture/extern_mod2.rs create mode 100644 gcc/testsuite/rust/compile/torture/float1.rs create mode 100644 gcc/testsuite/rust/compile/torture/float_types.rs create mode 100644 gcc/testsuite/rust/compile/torture/forward_decl_1.rs create mode 100644 gcc/testsuite/rust/compile/torture/forward_decl_2.rs create mode 100644 gcc/testsuite/rust/compile/torture/forward_decl_3-unsafe.rs create mode 100644 gcc/testsuite/rust/compile/torture/forward_decl_3.rs create mode 100644 gcc/testsuite/rust/compile/torture/forward_decl_4.rs create mode 100644 gcc/testsuite/rust/compile/torture/forward_decl_5.rs create mode 100644 gcc/testsuite/rust/compile/torture/func1.rs create mode 100644 gcc/testsuite/rust/compile/torture/func2.rs create mode 100644 gcc/testsuite/rust/compile/torture/function_reference1.rs create mode 100644 gcc/testsuite/rust/compile/torture/function_reference2.rs create mode 100644 gcc/testsuite/rust/compile/torture/function_reference3.rs create mode 100644 gcc/testsuite/rust/compile/torture/function_reference4.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics1.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics10.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics11.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics12.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics13.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics14.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics15.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics16.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics17.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics18.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics19.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics2.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics20.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics21.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics22.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics23.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics24.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics25.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics26.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics27.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics28.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics29.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics3.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics30.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics31.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics32.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics4.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics5.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics6.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics7.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics8.rs create mode 100644 gcc/testsuite/rust/compile/torture/generics9.rs create mode 100644 gcc/testsuite/rust/compile/torture/grouped_expr_function.rs create mode 100644 gcc/testsuite/rust/compile/torture/identifier-missing-impl-1.rs create mode 100644 gcc/testsuite/rust/compile/torture/if.rs create mode 100644 gcc/testsuite/rust/compile/torture/if_elif.rs create mode 100644 gcc/testsuite/rust/compile/torture/if_elif_else_expr1.rs create mode 100644 gcc/testsuite/rust/compile/torture/if_else.rs create mode 100644 gcc/testsuite/rust/compile/torture/ifunaryexpr.rs create mode 100644 gcc/testsuite/rust/compile/torture/impl_block1.rs create mode 100644 gcc/testsuite/rust/compile/torture/impl_block2.rs create mode 100644 gcc/testsuite/rust/compile/torture/impl_block3.rs create mode 100644 gcc/testsuite/rust/compile/torture/impl_block_unused.rs create mode 100644 gcc/testsuite/rust/compile/torture/implicit_returns1.rs create mode 100644 gcc/testsuite/rust/compile/torture/infer_type1.rs create mode 100644 gcc/testsuite/rust/compile/torture/inner_attributes.rs create mode 100644 gcc/testsuite/rust/compile/torture/integer_inference_var1.rs create mode 100644 gcc/testsuite/rust/compile/torture/integer_inference_var2.rs create mode 100644 gcc/testsuite/rust/compile/torture/integer_inference_var3.rs create mode 100644 gcc/testsuite/rust/compile/torture/integer_inference_var4.rs create mode 100644 gcc/testsuite/rust/compile/torture/integer_inference_var5.rs create mode 100644 gcc/testsuite/rust/compile/torture/integer_types.rs create mode 100644 gcc/testsuite/rust/compile/torture/intrinsics-1.rs create mode 100644 gcc/testsuite/rust/compile/torture/intrinsics-2.rs create mode 100644 gcc/testsuite/rust/compile/torture/isolated_cr_block_comment.rs create mode 100644 gcc/testsuite/rust/compile/torture/isolated_cr_line_comment.rs create mode 100644 gcc/testsuite/rust/compile/torture/issue-1024.rs create mode 100644 gcc/testsuite/rust/compile/torture/issue-1075.rs create mode 100644 gcc/testsuite/rust/compile/torture/issue-1432.rs create mode 100644 gcc/testsuite/rust/compile/torture/issue-1434.rs create mode 100644 gcc/testsuite/rust/compile/torture/issue-368.rs create mode 100644 gcc/testsuite/rust/compile/torture/issue-808.rs create mode 100644 gcc/testsuite/rust/compile/torture/issue-862.rs create mode 100644 gcc/testsuite/rust/compile/torture/issue-893-2.rs create mode 100644 gcc/testsuite/rust/compile/torture/issue-893.rs create mode 100644 gcc/testsuite/rust/compile/torture/lazybooleanexpr_function.rs create mode 100644 gcc/testsuite/rust/compile/torture/lifetime1.rs create mode 100644 gcc/testsuite/rust/compile/torture/literals1.rs create mode 100644 gcc/testsuite/rust/compile/torture/loop1.rs create mode 100644 gcc/testsuite/rust/compile/torture/loop2.rs create mode 100644 gcc/testsuite/rust/compile/torture/loop3.rs create mode 100644 gcc/testsuite/rust/compile/torture/loop4.rs create mode 100644 gcc/testsuite/rust/compile/torture/loop5.rs create mode 100644 gcc/testsuite/rust/compile/torture/loop6.rs create mode 100644 gcc/testsuite/rust/compile/torture/loop7.rs create mode 100644 gcc/testsuite/rust/compile/torture/macro-issue1403.rs create mode 100644 gcc/testsuite/rust/compile/torture/macro-issue1426.rs create mode 100644 gcc/testsuite/rust/compile/torture/macro_as_expr.rs create mode 100644 gcc/testsuite/rust/compile/torture/match1.rs create mode 100644 gcc/testsuite/rust/compile/torture/methods1.rs create mode 100644 gcc/testsuite/rust/compile/torture/methods2.rs create mode 100644 gcc/testsuite/rust/compile/torture/methods3.rs create mode 100644 gcc/testsuite/rust/compile/torture/mod-nameresolve.rs create mode 100644 gcc/testsuite/rust/compile/torture/mod1.rs create mode 100644 gcc/testsuite/rust/compile/torture/mod2.rs create mode 100644 gcc/testsuite/rust/compile/torture/mod3.rs create mode 100644 gcc/testsuite/rust/compile/torture/modules/mod.rs create mode 100644 gcc/testsuite/rust/compile/torture/modules/valid_path.rs create mode 100644 gcc/testsuite/rust/compile/torture/must_use1.rs create mode 100644 gcc/testsuite/rust/compile/torture/must_use2.rs create mode 100644 gcc/testsuite/rust/compile/torture/name_resolve1.rs create mode 100644 gcc/testsuite/rust/compile/torture/negation_function.rs create mode 100644 gcc/testsuite/rust/compile/torture/nested_fn1.rs create mode 100644 gcc/testsuite/rust/compile/torture/nested_fn2.rs create mode 100644 gcc/testsuite/rust/compile/torture/nested_struct1.rs create mode 100644 gcc/testsuite/rust/compile/torture/never_type1.rs create mode 100644 gcc/testsuite/rust/compile/torture/not_shebang.rs create mode 100644 gcc/testsuite/rust/compile/torture/not_shebang_block_comment.rs create mode 100644 gcc/testsuite/rust/compile/torture/not_shebang_comment.rs create mode 100644 gcc/testsuite/rust/compile/torture/not_shebang_multiline_comment.rs create mode 100644 gcc/testsuite/rust/compile/torture/not_shebang_spaces.rs create mode 100644 gcc/testsuite/rust/compile/torture/parameter_usage1.rs create mode 100644 gcc/testsuite/rust/compile/torture/parens1.rs create mode 100644 gcc/testsuite/rust/compile/torture/pointer1.rs create mode 100644 gcc/testsuite/rust/compile/torture/primconsts.rs create mode 100644 gcc/testsuite/rust/compile/torture/prims_struct_eq.rs create mode 100644 gcc/testsuite/rust/compile/torture/range-lang-item1.rs create mode 100644 gcc/testsuite/rust/compile/torture/raw_identifiers.rs create mode 100644 gcc/testsuite/rust/compile/torture/raw_identifiers_keywords.rs create mode 100644 gcc/testsuite/rust/compile/torture/recursive_fn1.rs create mode 100644 gcc/testsuite/rust/compile/torture/return_function.rs create mode 100644 gcc/testsuite/rust/compile/torture/scoping1.rs create mode 100644 gcc/testsuite/rust/compile/torture/self_type1.rs create mode 100644 gcc/testsuite/rust/compile/torture/shadow1.rs create mode 100644 gcc/testsuite/rust/compile/torture/shadow2.rs create mode 100755 gcc/testsuite/rust/compile/torture/shebang.rs create mode 100755 gcc/testsuite/rust/compile/torture/shebang_plus_attr.rs create mode 100755 gcc/testsuite/rust/compile/torture/shebang_plus_attr2.rs create mode 100644 gcc/testsuite/rust/compile/torture/static_function.rs create mode 100644 gcc/testsuite/rust/compile/torture/static_var1.rs create mode 100644 gcc/testsuite/rust/compile/torture/stmt_with_block1.rs create mode 100644 gcc/testsuite/rust/compile/torture/str1.rs create mode 100644 gcc/testsuite/rust/compile/torture/struct_access1.rs create mode 100644 gcc/testsuite/rust/compile/torture/struct_base_init_1.rs create mode 100644 gcc/testsuite/rust/compile/torture/struct_decl.rs create mode 100644 gcc/testsuite/rust/compile/torture/struct_init.rs create mode 100644 gcc/testsuite/rust/compile/torture/struct_init_10.rs create mode 100644 gcc/testsuite/rust/compile/torture/struct_init_11.rs create mode 100644 gcc/testsuite/rust/compile/torture/struct_init_2.rs create mode 100644 gcc/testsuite/rust/compile/torture/struct_init_3.rs create mode 100644 gcc/testsuite/rust/compile/torture/struct_init_4.rs create mode 100644 gcc/testsuite/rust/compile/torture/struct_init_5.rs create mode 100644 gcc/testsuite/rust/compile/torture/struct_init_6.rs create mode 100644 gcc/testsuite/rust/compile/torture/struct_init_7.rs create mode 100644 gcc/testsuite/rust/compile/torture/struct_init_8.rs create mode 100644 gcc/testsuite/rust/compile/torture/struct_init_9.rs create mode 100644 gcc/testsuite/rust/compile/torture/top_attr.rs create mode 100644 gcc/testsuite/rust/compile/torture/traits1.rs create mode 100644 gcc/testsuite/rust/compile/torture/traits10.rs create mode 100644 gcc/testsuite/rust/compile/torture/traits11.rs create mode 100644 gcc/testsuite/rust/compile/torture/traits12.rs create mode 100644 gcc/testsuite/rust/compile/torture/traits13.rs create mode 100644 gcc/testsuite/rust/compile/torture/traits14.rs create mode 100644 gcc/testsuite/rust/compile/torture/traits15.rs create mode 100644 gcc/testsuite/rust/compile/torture/traits16.rs create mode 100644 gcc/testsuite/rust/compile/torture/traits17.rs create mode 100644 gcc/testsuite/rust/compile/torture/traits18.rs create mode 100644 gcc/testsuite/rust/compile/torture/traits19.rs create mode 100644 gcc/testsuite/rust/compile/torture/traits2.rs create mode 100644 gcc/testsuite/rust/compile/torture/traits3.rs create mode 100644 gcc/testsuite/rust/compile/torture/traits4.rs create mode 100644 gcc/testsuite/rust/compile/torture/traits5.rs create mode 100644 gcc/testsuite/rust/compile/torture/traits6.rs create mode 100644 gcc/testsuite/rust/compile/torture/traits7.rs create mode 100644 gcc/testsuite/rust/compile/torture/traits8.rs create mode 100644 gcc/testsuite/rust/compile/torture/traits9.rs create mode 100644 gcc/testsuite/rust/compile/torture/transmute-size-check-1.rs create mode 100644 gcc/testsuite/rust/compile/torture/transmute1.rs create mode 100644 gcc/testsuite/rust/compile/torture/tuple1.rs create mode 100644 gcc/testsuite/rust/compile/torture/tuple2.rs create mode 100644 gcc/testsuite/rust/compile/torture/tuple3.rs create mode 100644 gcc/testsuite/rust/compile/torture/tuple_enum_variants.rs create mode 100644 gcc/testsuite/rust/compile/torture/tuple_field_access.rs create mode 100644 gcc/testsuite/rust/compile/torture/tuple_function.rs create mode 100644 gcc/testsuite/rust/compile/torture/tuple_index.rs create mode 100644 gcc/testsuite/rust/compile/torture/tuple_struct1.rs create mode 100644 gcc/testsuite/rust/compile/torture/tuple_struct2.rs create mode 100644 gcc/testsuite/rust/compile/torture/tuple_struct_unit.rs create mode 100644 gcc/testsuite/rust/compile/torture/tuple_struct_unused.rs create mode 100644 gcc/testsuite/rust/compile/torture/type-alias1.rs create mode 100644 gcc/testsuite/rust/compile/torture/type-alias2.rs create mode 100644 gcc/testsuite/rust/compile/torture/type_infer1.rs create mode 100644 gcc/testsuite/rust/compile/torture/type_infer2.rs create mode 100644 gcc/testsuite/rust/compile/torture/type_infer3.rs create mode 100644 gcc/testsuite/rust/compile/torture/type_infer4.rs create mode 100644 gcc/testsuite/rust/compile/torture/type_infer5.rs create mode 100644 gcc/testsuite/rust/compile/torture/type_infer6.rs create mode 100644 gcc/testsuite/rust/compile/torture/unary_operators.rs create mode 100644 gcc/testsuite/rust/compile/torture/undended-string-1.rs create mode 100644 gcc/testsuite/rust/compile/torture/undended-string-2.rs create mode 100644 gcc/testsuite/rust/compile/torture/underscore_id.rs create mode 100644 gcc/testsuite/rust/compile/torture/union.rs create mode 100644 gcc/testsuite/rust/compile/torture/union_union.rs create mode 100644 gcc/testsuite/rust/compile/torture/unit_type1.rs create mode 100644 gcc/testsuite/rust/compile/torture/unit_type2.rs create mode 100644 gcc/testsuite/rust/compile/torture/unit_type3.rs create mode 100644 gcc/testsuite/rust/compile/torture/unit_type4.rs create mode 100644 gcc/testsuite/rust/compile/torture/unit_type5.rs create mode 100644 gcc/testsuite/rust/compile/torture/unsafe1.rs create mode 100644 gcc/testsuite/rust/compile/torture/unsafe2.rs create mode 100644 gcc/testsuite/rust/compile/torture/unsafe3.rs create mode 100644 gcc/testsuite/rust/compile/torture/unsafe4.rs create mode 100644 gcc/testsuite/rust/compile/torture/unused.rs create mode 100644 gcc/testsuite/rust/compile/torture/unused1.rs create mode 100644 gcc/testsuite/rust/compile/torture/unused_struct.rs create mode 100644 gcc/testsuite/rust/compile/torture/unused_struct_field.rs create mode 100644 gcc/testsuite/rust/compile/torture/usize1.rs create mode 100644 gcc/testsuite/rust/compile/torture/very-broken-attr-string.rs create mode 100644 gcc/testsuite/rust/compile/torture/while_function.rs create mode 100644 gcc/testsuite/rust/compile/traits1.rs create mode 100644 gcc/testsuite/rust/compile/traits10.rs create mode 100644 gcc/testsuite/rust/compile/traits11.rs create mode 100644 gcc/testsuite/rust/compile/traits12.rs create mode 100644 gcc/testsuite/rust/compile/traits2.rs create mode 100644 gcc/testsuite/rust/compile/traits3.rs create mode 100644 gcc/testsuite/rust/compile/traits4.rs create mode 100644 gcc/testsuite/rust/compile/traits5.rs create mode 100644 gcc/testsuite/rust/compile/traits6.rs create mode 100644 gcc/testsuite/rust/compile/traits7.rs create mode 100644 gcc/testsuite/rust/compile/traits8.rs create mode 100644 gcc/testsuite/rust/compile/traits9.rs create mode 100644 gcc/testsuite/rust/compile/tuple1.rs create mode 100644 gcc/testsuite/rust/compile/tuple_struct1.rs create mode 100644 gcc/testsuite/rust/compile/tuple_struct2.rs create mode 100644 gcc/testsuite/rust/compile/tuple_struct3.rs create mode 100644 gcc/testsuite/rust/compile/type-alias1.rs create mode 100644 gcc/testsuite/rust/compile/type-bindings1.rs create mode 100644 gcc/testsuite/rust/compile/unary_negation.rs create mode 100644 gcc/testsuite/rust/compile/unary_not.rs create mode 100644 gcc/testsuite/rust/compile/unconstrained_type_param.rs create mode 100644 gcc/testsuite/rust/compile/unicode_escape.rs create mode 100644 gcc/testsuite/rust/compile/unsafe1.rs create mode 100644 gcc/testsuite/rust/compile/unsafe10.rs create mode 100644 gcc/testsuite/rust/compile/unsafe2.rs create mode 100644 gcc/testsuite/rust/compile/unsafe3.rs create mode 100644 gcc/testsuite/rust/compile/unsafe4.rs create mode 100644 gcc/testsuite/rust/compile/unsafe5.rs create mode 100644 gcc/testsuite/rust/compile/unsafe6.rs create mode 100644 gcc/testsuite/rust/compile/unsafe7.rs create mode 100644 gcc/testsuite/rust/compile/unsafe8.rs create mode 100644 gcc/testsuite/rust/compile/unsafe9.rs create mode 100644 gcc/testsuite/rust/compile/unterminated_c_comment.rs create mode 100644 gcc/testsuite/rust/compile/use_1.rs create mode 100644 gcc/testsuite/rust/compile/usize1.rs create mode 100644 gcc/testsuite/rust/compile/xfail/lifetime_param.rs create mode 100644 gcc/testsuite/rust/compile/xfail/struct_field_vis.rs create mode 100644 gcc/testsuite/rust/compile/xfail/xfail.exp diff --git a/gcc/testsuite/rust/compile/abi-options1.rs b/gcc/testsuite/rust/compile/abi-options1.rs new file mode 100644 index 00000000000..a4b6241dc15 --- /dev/null +++ b/gcc/testsuite/rust/compile/abi-options1.rs @@ -0,0 +1,7 @@ +extern "foobar" { + // { dg-error "unknown ABI option" "" { target *-*-* } .-1 } + fn printf(s: *const i8, ...); +} + +pub extern "baz" fn test() {} +// { dg-error "unknown ABI option" "" { target *-*-* } .-1 } diff --git a/gcc/testsuite/rust/compile/array3.rs b/gcc/testsuite/rust/compile/array3.rs new file mode 100644 index 00000000000..a56be9a0e8b --- /dev/null +++ b/gcc/testsuite/rust/compile/array3.rs @@ -0,0 +1,4 @@ +fn foo(state: &mut [u32; 16], a: usize) { + // { dg-warning "function is never used: .foo." "" { target *-*-* } .-1 } + state[a] = 1; +} diff --git a/gcc/testsuite/rust/compile/array_empty_list.rs b/gcc/testsuite/rust/compile/array_empty_list.rs new file mode 100644 index 00000000000..76e082a6d57 --- /dev/null +++ b/gcc/testsuite/rust/compile/array_empty_list.rs @@ -0,0 +1,4 @@ +fn main() { + let arr = []; + // { dg-error "type annotations needed" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/arrays1.rs b/gcc/testsuite/rust/compile/arrays1.rs new file mode 100644 index 00000000000..714a6be7afb --- /dev/null +++ b/gcc/testsuite/rust/compile/arrays1.rs @@ -0,0 +1,4 @@ +fn main() { + let xs: [i32; 5] = [1, 2, 3, 4, 5]; + let a: bool = xs[0]; // { dg-error "expected .bool. got .i32." } +} diff --git a/gcc/testsuite/rust/compile/arrays2.rs b/gcc/testsuite/rust/compile/arrays2.rs new file mode 100644 index 00000000000..c96f4f7d820 --- /dev/null +++ b/gcc/testsuite/rust/compile/arrays2.rs @@ -0,0 +1,5 @@ +// { dg-additional-options "-w" } +fn main() { + let array: [i32; 5] = [1, 2, 3]; + // { dg-error "expected an array with a fixed size of 5 elements, found one with 3 elements" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/attr-mismatch-crate-name.rs b/gcc/testsuite/rust/compile/attr-mismatch-crate-name.rs new file mode 100644 index 00000000000..1d406031fee --- /dev/null +++ b/gcc/testsuite/rust/compile/attr-mismatch-crate-name.rs @@ -0,0 +1,4 @@ +// { dg-additional-options "-fdump-tree-gimple" } +#![crate_name = "specified_name"] +// { dg-final { scan-tree-dump-times {specified_name::main} 1 gimple } } +fn main() {} diff --git a/gcc/testsuite/rust/compile/attr_cold.rs b/gcc/testsuite/rust/compile/attr_cold.rs new file mode 100644 index 00000000000..f705ea9b2ff --- /dev/null +++ b/gcc/testsuite/rust/compile/attr_cold.rs @@ -0,0 +1,12 @@ +// { dg-additional-options "-fdump-tree-gimple" } +#[cold] +fn cold_function() -> i32 { + 42 +} + +fn main() -> i32 { + // { dg-final { scan-tree-dump-times {__attribute__\(\(cdecl, cold\)\)} 1 gimple } } + cold_function(); + + 0 +} diff --git a/gcc/testsuite/rust/compile/attr_deprecated.rs b/gcc/testsuite/rust/compile/attr_deprecated.rs new file mode 100644 index 00000000000..01bc9c41502 --- /dev/null +++ b/gcc/testsuite/rust/compile/attr_deprecated.rs @@ -0,0 +1,14 @@ +#[deprecated(since="1.0", note="do not use this function")] +fn test1() {} + +#[deprecated] +fn test() {} + +#[deprecated = "a different message"] +fn test2() {} + +fn main() { + test(); // { dg-warning ".attr_deprecated::test. is deprecated" } + test1(); // { dg-warning ".attr_deprecated::test1. is deprecated: do not use this function" } + test2(); // { dg-warning ".attr_deprecated::test2. is deprecated: a different message" } +} diff --git a/gcc/testsuite/rust/compile/attr_deprecated_2.rs b/gcc/testsuite/rust/compile/attr_deprecated_2.rs new file mode 100644 index 00000000000..66f4ce3b076 --- /dev/null +++ b/gcc/testsuite/rust/compile/attr_deprecated_2.rs @@ -0,0 +1,11 @@ +#[deprecated(since="1.0")] +fn test1() {} + +// { dg-excess-errors "unknown meta item ...." } +#[deprecated(invalid="invalid")] +fn test2() {} + +fn main() { + test1(); // { dg-warning ".attr_deprecated_2::test1. is deprecated" } + test2(); +} diff --git a/gcc/testsuite/rust/compile/bad-crate-name.rs b/gcc/testsuite/rust/compile/bad-crate-name.rs new file mode 100644 index 00000000000..6c59c255cc2 --- /dev/null +++ b/gcc/testsuite/rust/compile/bad-crate-name.rs @@ -0,0 +1,4 @@ +// { dg-additional-options "-frust-crate=bad+name" } +// { dg-excess-errors "invalid crate name: ...." } +// { dg-excess-errors "unrecognized command-line option ...." } +fn main() {} diff --git a/gcc/testsuite/rust/compile/bad=file-name.rs b/gcc/testsuite/rust/compile/bad=file-name.rs new file mode 100644 index 00000000000..cfbebb0698d --- /dev/null +++ b/gcc/testsuite/rust/compile/bad=file-name.rs @@ -0,0 +1,7 @@ +// { dg-additional-options "-fdump-tree-gimple -frust-crate=good_name" } +pub fn does_nothing() {} +fn main() { + does_nothing() +} +// { dg-final { scan-tree-dump-times {good_name::does_nothing} 2 gimple } } +// { dg-final { scan-tree-dump-times {good_name::main} 1 gimple } } diff --git a/gcc/testsuite/rust/compile/bad_as_bool_char.rs b/gcc/testsuite/rust/compile/bad_as_bool_char.rs new file mode 100644 index 00000000000..91a28eebe00 --- /dev/null +++ b/gcc/testsuite/rust/compile/bad_as_bool_char.rs @@ -0,0 +1,18 @@ +pub fn main () +{ + let t = true; + let f = false; + let fone = t as f32; // { dg-error "invalid cast" } + let fzero = f as f64; // { dg-error "invalid cast" } + + let nb = 0u8 as bool; // { dg-error "invalid cast" } + let nc = true as char; // { dg-error "invalid cast" } + + let a = 'a'; + let b = 'b'; + let fa = a as f32; // { dg-error "invalid cast" } + let bb = b as bool; // { dg-error "invalid cast" } + + let t32: u32 = 33; + let ab = t32 as char; // { dg-error "invalid cast" } +} diff --git a/gcc/testsuite/rust/compile/bad_file_name.txt.rs b/gcc/testsuite/rust/compile/bad_file_name.txt.rs new file mode 100644 index 00000000000..56e2093b27c --- /dev/null +++ b/gcc/testsuite/rust/compile/bad_file_name.txt.rs @@ -0,0 +1,3 @@ +// { dg-excess-errors "invalid crate name: ...." } +// { dg-bogus "unrecognized command-line option ...." } +fn main() {} diff --git a/gcc/testsuite/rust/compile/bad_inner_doc.rs b/gcc/testsuite/rust/compile/bad_inner_doc.rs new file mode 100644 index 00000000000..cfd166ce3ec --- /dev/null +++ b/gcc/testsuite/rust/compile/bad_inner_doc.rs @@ -0,0 +1,15 @@ +pub fn main () +{ + //! inner doc allowed + let _x = 42; + // { dg-error "inner doc" "" { target *-*-* } .+1 } + //! inner doc disallowed + mod module + { + /*! inner doc allowed */ + /// outer doc allowed + // { dg-error "inner doc" "" { target *-*-* } .+1 } + /*! but inner doc not here */ + mod x { } + } +} diff --git a/gcc/testsuite/rust/compile/bad_pub_enumitems.rs b/gcc/testsuite/rust/compile/bad_pub_enumitems.rs new file mode 100644 index 00000000000..e7fd5edb981 --- /dev/null +++ b/gcc/testsuite/rust/compile/bad_pub_enumitems.rs @@ -0,0 +1,47 @@ +pub enum E +{ + pub A { a: i32 }, // { dg-error "visibility qualifier" } + B (u8), + pub C, // { dg-error "visibility qualifier" } + D +} + +enum E1 +{ + A, + pub B = 42, // { dg-error "visibility qualifier" } + C = 3, + D, + pub E // { dg-error "visibility qualifier" } +} + +enum E2 +{ + pub A (u8, i32, u64), // { dg-error "visibility qualifier" } + B { a: u8, a: u8 } // { dg-error "duplicate field" }} +} + +fn main () +{ + enum EE + { + Alpha { alpha: i32 }, + pub Beta (u8), // { dg-error "visibility qualifier" } + pub Gamma, // { dg-error "visibility qualifier" } + Delta { delta: u32 } + } + + enum EE1 + { + pub Alpha, // { dg-error "visibility qualifier" } + Beta = 41, + pub Gamma = 3, // { dg-error "visibility qualifier" } + Delta, + } + + enum E2 + { + Alpha { a: u8, a: u8 }, // { dg-error "duplicate field" }} + pub Beta (u8, i32, u64) // { dg-error "visibility qualifier" } + } +} diff --git a/gcc/testsuite/rust/compile/bad_stmt_enums.rs b/gcc/testsuite/rust/compile/bad_stmt_enums.rs new file mode 100644 index 00000000000..7b09a94fd27 --- /dev/null +++ b/gcc/testsuite/rust/compile/bad_stmt_enums.rs @@ -0,0 +1,22 @@ +fn main () +{ + enum EE + { + Alpha { alpha: i32 }, + pub Beta (u8), + pub Gamma, + Gamma { gamma: u32 } // { dg-error "redefined" } + } + + struct EE2 { } + enum EE2 { } // { dg-error "redefined" } + + enum EE1 + { + pub Alpha, + Beta = 41, + Beta = 42, // { dg-error "redefined" } + pub Gamma = 3, + D, + } +} diff --git a/gcc/testsuite/rust/compile/bad_toplevel_enums.rs b/gcc/testsuite/rust/compile/bad_toplevel_enums.rs new file mode 100644 index 00000000000..b655e30a93d --- /dev/null +++ b/gcc/testsuite/rust/compile/bad_toplevel_enums.rs @@ -0,0 +1,19 @@ +pub enum E +{ + pub A { a: i32 }, + B (u8), + pub C, + B // { dg-error "redefined" } +} + +enum E2 { } +struct E2 { } // { dg-error "redefined" } + +enum E1 +{ + A, + pub B = 42, + C = 3, + A { a: u8 }, // { dg-error "redefined" } + pub D +} diff --git a/gcc/testsuite/rust/compile/bad_tuple_index.rs b/gcc/testsuite/rust/compile/bad_tuple_index.rs new file mode 100644 index 00000000000..c3bd1e91d10 --- /dev/null +++ b/gcc/testsuite/rust/compile/bad_tuple_index.rs @@ -0,0 +1,66 @@ +fn main() +{ + // tuples + let z = (); + + let o = (0,); + /* Binary, Octal and Hex literals are invalid. */ + let _fb = o.0b0; // { dg-error "tuple index should be a pure decimal literal" } + let _fo = o.0o0; // { dg-error "tuple index should be a pure decimal literal" } + let _fh = o.0x0; // { dg-error "tuple index should be a pure decimal literal" } + + /* No underscores. */ + let _fua = o.0_; // { dg-error "tuple index should be a pure decimal literal" } + + /* Suffix is not allowed. */ + let _fu8 = o.0u8; // { dg-error "tuple index should be a pure decimal literal" } + let _fi8 = o.0i8; // { dg-error "tuple index should be a pure decimal literal" } + let _fu16 = o.0u16; // { dg-error "tuple index should be a pure decimal literal" } + let _fi16 = o.0i16; // { dg-error "tuple index should be a pure decimal literal" } + let _fu32 = o.0u32; // { dg-error "tuple index should be a pure decimal literal" } + let _fi32 = o.0i32; // { dg-error "tuple index should be a pure decimal literal" } + let _fu64 = o.0u64; // { dg-error "tuple index should be a pure decimal literal" } + let _fi64 = o.0i64; // { dg-error "tuple index should be a pure decimal literal" } + let _fu128 = o.0u128; // { dg-error "tuple index should be a pure decimal literal" } + let _fi128 = o.0i128; // { dg-error "tuple index should be a pure decimal literal" } + let _fusize = o.0usize; // { dg-error "tuple index should be a pure decimal literal" } + let _fisize = o.0isize; // { dg-error "tuple index should be a pure decimal literal" } + + let t = (0,1); + /* No extra zero prefix. */ + let _s = t.01; // { dg-error "tuple index should be a pure decimal literal" } + + let m = (0,1,2,3,4,5,6,7,8,9,10); + /* No extra zero prefix. */ + let _l = m.010; // { dg-error "tuple index should be a pure decimal literal" } + + /* No underscores. */ + let _lu = m.1_0; // { dg-error "tuple index should be a pure decimal literal" } + + // tuple structs + struct E(); + let _e = E(); + + struct O(i32); + let so = O(0); + /* No leading zeros, no underscores. */ + let _sf = so.0_0; // { dg-error "tuple index should be a pure decimal literal" } + /* Binary, Octal and Hex literals are invalid. */ + let _sb = so.0b0; // { dg-error "tuple index should be a pure decimal literal" } + let _so = so.0o0; // { dg-error "tuple index should be a pure decimal literal" } + let _sh = so.0x0; // { dg-error "tuple index should be a pure decimal literal" } + + struct T(i32,i32); + let st = T(0,1); + /* Suffix is not allowed. */ + let _stfu32 = st.1u32; // { dg-error "tuple index should be a pure decimal literal" } + let _stfi32 = st.1i32; // { dg-error "tuple index should be a pure decimal literal" } + + struct M(i32,i32,i32,i32,i32,i32,i32,i32,i32,i32,i32); + let sm = M(0,1,2,3,4,5,6,7,8,9,10); + /* No underscores. */ + let _sl2 = sm.1_0; // { dg-error "tuple index should be a pure decimal literal" } + let _sl3 = sm.10_; // { dg-error "tuple index should be a pure decimal literal" } + + z +} diff --git a/gcc/testsuite/rust/compile/bad_type1.rs b/gcc/testsuite/rust/compile/bad_type1.rs new file mode 100644 index 00000000000..93de439704f --- /dev/null +++ b/gcc/testsuite/rust/compile/bad_type1.rs @@ -0,0 +1,3 @@ +fn main() { + let logical: bool = 123; // { dg-error "expected .bool. got .." } +} diff --git a/gcc/testsuite/rust/compile/bad_type2.rs b/gcc/testsuite/rust/compile/bad_type2.rs new file mode 100644 index 00000000000..e47b8aac0e7 --- /dev/null +++ b/gcc/testsuite/rust/compile/bad_type2.rs @@ -0,0 +1,14 @@ +fn test(x: i32) -> i32 { + return x + 1; +} + +fn main() { + let mut an_integer = 5; + an_integer = test(1) + 3; + + let mut x; + x = 1; + x = true; // { dg-error "expected .. got .bool." } + + let call_test = test(1); +} diff --git a/gcc/testsuite/rust/compile/break1.rs b/gcc/testsuite/rust/compile/break1.rs new file mode 100644 index 00000000000..91cabffa894 --- /dev/null +++ b/gcc/testsuite/rust/compile/break1.rs @@ -0,0 +1,6 @@ +fn main() { + let a; + a = 1; + break a; // { dg-error "cannot 'break' outside of a loop" } + // { dg-error "failed to type resolve expression" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/break2.rs b/gcc/testsuite/rust/compile/break2.rs new file mode 100644 index 00000000000..5ac806aeb9e --- /dev/null +++ b/gcc/testsuite/rust/compile/break2.rs @@ -0,0 +1,15 @@ +fn main() { + let mut a = 1; + let mut b = 1; + + let mut c; + while b > 10 { + if (b == 2) { + break b; // { dg-error "can only break with a value inside 'loop'" } + // { dg-error "failed to type resolve expression" "" { target *-*-* } .-1 } + } + c = a + b; + a = b; + b = c; + } +} diff --git a/gcc/testsuite/rust/compile/builtin_macro_compile_error.rs b/gcc/testsuite/rust/compile/builtin_macro_compile_error.rs new file mode 100644 index 00000000000..9d224406a3e --- /dev/null +++ b/gcc/testsuite/rust/compile/builtin_macro_compile_error.rs @@ -0,0 +1,13 @@ +#[rustc_builtin_macro] +macro_rules! compile_error { + () => {{}}; +} + +fn main () { + let message = "error message"; + compile_error! (message); // { dg-error "argument must be a string literal" "" } + compile_error! (); // { dg-error "macro takes 1 argument" "" } + compile_error! ("a", "b"); // { dg-error "macro takes 1 argument" "" } + compile_error! ("expected error message"); // { dg-error "expected error message" } + compile_error! ("expected error message",); // { dg-error "expected error message" } +} diff --git a/gcc/testsuite/rust/compile/builtin_macro_concat.rs b/gcc/testsuite/rust/compile/builtin_macro_concat.rs new file mode 100644 index 00000000000..9b878af764d --- /dev/null +++ b/gcc/testsuite/rust/compile/builtin_macro_concat.rs @@ -0,0 +1,17 @@ +#[rustc_builtin_macro] +macro_rules! concat { + () => {{}}; +} + +fn main() { + let not_literal = "identifier"; + concat!(); + concat! (,); // { dg-error "argument must be a constant literal" } + concat!(not_literal); // { dg-error "argument must be a constant literal" } + concat!("message"); + concat!("message",); + concat!("message", 1, true, false, 1.0, 10usize, 2000u64); + concat!("message", 1, true, false, 1.0, 10usize, 2000u64,); + concat! ("m", not_literal); // { dg-error "argument must be a constant literal" } + concat!(not_literal invalid 'm' !!,); // { dg-error "argument must be a constant literal" } +} diff --git a/gcc/testsuite/rust/compile/builtin_macro_env.rs b/gcc/testsuite/rust/compile/builtin_macro_env.rs new file mode 100644 index 00000000000..289e6db2cf1 --- /dev/null +++ b/gcc/testsuite/rust/compile/builtin_macro_env.rs @@ -0,0 +1,20 @@ +#[rustc_builtin_macro] +macro_rules! env { + () => {{}}; +} + +fn main () { + let message = "error message"; + env! (message); // { dg-error "argument must be a string literal" "" } + env! (); // { dg-error "env! takes 1 or 2 arguments" "" } + env! (,); // { dg-error "argument must be a string literal" "" } + env! (1); // { dg-error "argument must be a string literal" "" } + env! ("NOT_DEFINED"); // { dg-error "environment variable 'NOT_DEFINED' not defined" "" } + env! ("NOT_DEFINED",); // { dg-error "environment variable 'NOT_DEFINED' not defined" "" } + env! ("NOT_DEFINED", 1); // { dg-error "argument must be a string literal" "" } + env! ("NOT_DEFINED", "two", "three"); // { dg-error "env! takes 1 or 2 arguments" "" } + env! ("NOT_DEFINED" "expected error message"); // { dg-error "expected token: ','" "" } + env! ("NOT_DEFINED", "expected error message"); // { dg-error "expected error message" "" } + env! ("NOT_DEFINED", "expected error message",); // { dg-error "expected error message" "" } + env! (1, "two"); // { dg-error "argument must be a string literal" "" } +} diff --git a/gcc/testsuite/rust/compile/builtin_macro_include_bytes.rs b/gcc/testsuite/rust/compile/builtin_macro_include_bytes.rs new file mode 100644 index 00000000000..38716d33bcd --- /dev/null +++ b/gcc/testsuite/rust/compile/builtin_macro_include_bytes.rs @@ -0,0 +1,13 @@ +#[rustc_builtin_macro] +macro_rules! include_bytes { + () => {{}}; +} + +fn main () { + let file = "include.txt"; + include_bytes! (file); // { dg-error "argument must be a string literal" "" } + include_bytes! (); // { dg-error "macro takes 1 argument" "" } + include_bytes! ("foo.txt", "bar.txt"); // { dg-error "macro takes 1 argument" "" } + include_bytes! ("builtin_macro_include_bytes.rs"); // ok + include_bytes! ("builtin_macro_include_bytes.rs",); // trailing comma ok +} diff --git a/gcc/testsuite/rust/compile/builtin_macro_include_str.rs b/gcc/testsuite/rust/compile/builtin_macro_include_str.rs new file mode 100644 index 00000000000..38f5e3b7334 --- /dev/null +++ b/gcc/testsuite/rust/compile/builtin_macro_include_str.rs @@ -0,0 +1,13 @@ +#[rustc_builtin_macro] +macro_rules! include_str { + () => {{}}; +} + +fn main () { + let file = "include.txt"; + include_str! (file); // { dg-error "argument must be a string literal" "" } + include_str! (); // { dg-error "macro takes 1 argument" "" } + include_str! ("foo.txt", "bar.txt"); // { dg-error "macro takes 1 argument" "" } + include_str! ("builtin_macro_include_str.rs"); // ok + include_str! ("builtin_macro_include_str.rs",); // trailing comma ok +} diff --git a/gcc/testsuite/rust/compile/builtin_macro_not_found.rs b/gcc/testsuite/rust/compile/builtin_macro_not_found.rs new file mode 100644 index 00000000000..1a3228b9284 --- /dev/null +++ b/gcc/testsuite/rust/compile/builtin_macro_not_found.rs @@ -0,0 +1,4 @@ +#[rustc_builtin_macro] +macro_rules! crabby_crab_carb { // { dg-error "cannot find a built-in macro with name .crabby_crab_carb." } + () => {{}}; +} diff --git a/gcc/testsuite/rust/compile/bytecharstring.rs b/gcc/testsuite/rust/compile/bytecharstring.rs new file mode 100644 index 00000000000..9242e2c5a0b --- /dev/null +++ b/gcc/testsuite/rust/compile/bytecharstring.rs @@ -0,0 +1,8 @@ +fn main () +{ + let _bc = b'\x80'; + let _bs = b"foo\x80bar"; + + let _c = '\xef'; // { dg-error "out of range" } + let _s = "Foo\xEFBar"; // { dg-error "out of range" } +} diff --git a/gcc/testsuite/rust/compile/canonical_paths1.rs b/gcc/testsuite/rust/compile/canonical_paths1.rs new file mode 100644 index 00000000000..193e7b5b698 --- /dev/null +++ b/gcc/testsuite/rust/compile/canonical_paths1.rs @@ -0,0 +1,25 @@ +// { dg-additional-options "-w -fdump-tree-gimple -frust-crate=example" } +struct Foo(i32); + +trait TR { + fn test(&self) -> i32; +} + +mod A { + impl ::Foo { + pub fn test(self) {} + // { dg-final { scan-tree-dump-times {example::A::::test} 2 gimple } } + } + + impl ::TR for ::Foo { + fn test(&self) -> i32 { + // { dg-final { scan-tree-dump-times {example::A::::test} 1 gimple } } + self.0 + } + } +} + +pub fn test() { + let a = Foo(123); + a.test(); +} diff --git a/gcc/testsuite/rust/compile/cast1.rs b/gcc/testsuite/rust/compile/cast1.rs new file mode 100644 index 00000000000..74c4b1eaac4 --- /dev/null +++ b/gcc/testsuite/rust/compile/cast1.rs @@ -0,0 +1,5 @@ +fn main() { + let a: i32 = 123; + let b = a as char; + // { dg-error "invalid cast .i32. to .char." "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/cfg1.rs b/gcc/testsuite/rust/compile/cfg1.rs new file mode 100644 index 00000000000..6984f04d1b9 --- /dev/null +++ b/gcc/testsuite/rust/compile/cfg1.rs @@ -0,0 +1,31 @@ +// { dg-additional-options "-w" } +extern "C" { + fn printf(s: *const i8, ...); +} + +#[cfg(A)] +fn test() { + unsafe { + let a = "test1\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } +} + +#[cfg(B)] +fn test() { + unsafe { + let a = "test2\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } +} + +fn main() { + test(); + // { dg-error "Cannot find path .test. in this scope" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/cfg2.rs b/gcc/testsuite/rust/compile/cfg2.rs new file mode 100644 index 00000000000..939384c5b7d --- /dev/null +++ b/gcc/testsuite/rust/compile/cfg2.rs @@ -0,0 +1,13 @@ +// { dg-additional-options "-w -frust-cfg=A" } +struct Foo; +impl Foo { + #[cfg(not(A))] + fn test(&self) {} +} + +fn main() { + let a = Foo; + a.test(); + // { dg-error "failed to resolve method for .test." "" { target *-*-* } .-1 } + // { dg-error "failed to type resolve expression" "" { target *-*-* } .-2 } +} diff --git a/gcc/testsuite/rust/compile/cfg3.rs b/gcc/testsuite/rust/compile/cfg3.rs new file mode 100644 index 00000000000..d6ffab6bfc6 --- /dev/null +++ b/gcc/testsuite/rust/compile/cfg3.rs @@ -0,0 +1,11 @@ +// { dg-additional-options "-w -frust-cfg=A -frust-cfg=B" } +struct Foo; +impl Foo { + #[cfg(all(A, B))] + fn test(&self) {} +} + +fn main() { + let a = Foo; + a.test(); +} diff --git a/gcc/testsuite/rust/compile/cfg4.rs b/gcc/testsuite/rust/compile/cfg4.rs new file mode 100644 index 00000000000..2834c277ddf --- /dev/null +++ b/gcc/testsuite/rust/compile/cfg4.rs @@ -0,0 +1,11 @@ +// { dg-additional-options "-w -frust-cfg=A" } +struct Foo; +impl Foo { + #[cfg(any(A, B))] + fn test(&self) {} +} + +fn main() { + let a = Foo; + a.test(); +} diff --git a/gcc/testsuite/rust/compile/cfg5.rs b/gcc/testsuite/rust/compile/cfg5.rs new file mode 100644 index 00000000000..1852efaf8df --- /dev/null +++ b/gcc/testsuite/rust/compile/cfg5.rs @@ -0,0 +1,11 @@ +// { dg-additional-options "-w -frust-cfg=A=\"B\"" } +struct Foo; +impl Foo { + #[cfg(A = "B")] + fn test(&self) {} +} + +fn main() { + let a = Foo; + a.test(); +} diff --git a/gcc/testsuite/rust/compile/compile.exp b/gcc/testsuite/rust/compile/compile.exp new file mode 100644 index 00000000000..13423d76c92 --- /dev/null +++ b/gcc/testsuite/rust/compile/compile.exp @@ -0,0 +1,35 @@ +# Copyright (C) 2021-2022 Free Software Foundation, Inc. + +# This program 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 of the License, or +# (at your option) any later version. +# +# This program 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 +# . + +# Compile tests, no torture testing. +# +# These tests raise errors in the front end; torture testing doesn't apply. + +# Load support procs. +load_lib rust-dg.exp + +# Initialize `dg'. +dg-init + +# Main loop. +set saved-dg-do-what-default ${dg-do-what-default} + +set dg-do-what-default "compile" +dg-runtest [lsort [glob -nocomplain $srcdir/$subdir/*.rs]] "" "" +set dg-do-what-default ${saved-dg-do-what-default} + +# All done. +dg-finish diff --git a/gcc/testsuite/rust/compile/complex-path1.rs b/gcc/testsuite/rust/compile/complex-path1.rs new file mode 100644 index 00000000000..54011bd6976 --- /dev/null +++ b/gcc/testsuite/rust/compile/complex-path1.rs @@ -0,0 +1,18 @@ +// { dg-additional-options "-w" } +mod a { + pub fn foo() {} +} + +mod b { + pub fn foo() { + super::a::foo(); + } +} + +mod foo { + pub struct bar(pub i32); +} + +fn test() -> crate::foo::bar { + foo::bar(123) +} diff --git a/gcc/testsuite/rust/compile/const-issue1440.rs b/gcc/testsuite/rust/compile/const-issue1440.rs new file mode 100644 index 00000000000..9b974b96bbb --- /dev/null +++ b/gcc/testsuite/rust/compile/const-issue1440.rs @@ -0,0 +1,76 @@ +// { dg-additional-options "-w" } + +mod intrinsics { + extern "rust-intrinsic" { + pub fn wrapping_add(a: T, b: T) -> T; + pub fn rotate_left(a: T, b: T) -> T; + pub fn rotate_right(a: T, b: T) -> T; + pub fn offset(ptr: *const T, count: isize) -> *const T; + } +} + +mod mem { + extern "rust-intrinsic" { + #[rustc_const_stable(feature = "const_transmute", since = "1.46.0")] + pub fn transmute(_: T) -> U; + pub fn size_of() -> usize; + } +} + +macro_rules! impl_uint { + ($($ty:ident = $lang:literal),*) => { + $( + impl $ty { + pub fn wrapping_add(self, rhs: Self) -> Self { + // intrinsics::wrapping_add(self, rhs) + self + rhs + } + + pub fn rotate_left(self, n: u32) -> Self { + unsafe { + intrinsics::rotate_left(self, n as Self) + } + } + + pub fn rotate_right(self, n: u32) -> Self { + unsafe { + intrinsics::rotate_right(self, n as Self) + } + } + + pub fn to_le(self) -> Self { + #[cfg(target_endian = "little")] + { + self + } + } + + pub const fn from_le_bytes(bytes: [u8; mem::size_of::()]) -> Self { + // { dg-error "only functions marked as .const. are allowed to be called from constant contexts" "" { target *-*-* } .-1 } + Self::from_le(Self::from_ne_bytes(bytes)) + } + + pub const fn from_le(x: Self) -> Self { + #[cfg(target_endian = "little")] + { + x + } + } + + pub const fn from_ne_bytes(bytes: [u8; mem::size_of::()]) -> Self { + // { dg-error "only functions marked as .const. are allowed to be called from constant contexts" "" { target *-*-* } .-1 } + unsafe { mem::transmute(bytes) } + } + } + )* + } +} + +impl_uint!( + u8 = "u8", + u16 = "u16", + u32 = "u32", + u64 = "u64", + u128 = "u128", + usize = "usize" +); diff --git a/gcc/testsuite/rust/compile/const1.rs b/gcc/testsuite/rust/compile/const1.rs new file mode 100644 index 00000000000..5f19c674c94 --- /dev/null +++ b/gcc/testsuite/rust/compile/const1.rs @@ -0,0 +1,6 @@ +fn bar() {} + +const fn foo() { + bar(); // { dg-error "only functions marked as .const. are allowed to be called from constant contexts" } +} + diff --git a/gcc/testsuite/rust/compile/const2.rs b/gcc/testsuite/rust/compile/const2.rs new file mode 100644 index 00000000000..17b6de573dd --- /dev/null +++ b/gcc/testsuite/rust/compile/const2.rs @@ -0,0 +1,7 @@ +// { dg-additional-options "-w" } + +const fn foo() { + const fn bar() {} + + bar(); +} diff --git a/gcc/testsuite/rust/compile/const3.rs b/gcc/testsuite/rust/compile/const3.rs new file mode 100644 index 00000000000..22dc3d356ca --- /dev/null +++ b/gcc/testsuite/rust/compile/const3.rs @@ -0,0 +1,7 @@ +fn size() -> usize { + 15 +} + +fn main() { + let a = [15; size()]; // { dg-error "only functions marked as .const. are allowed to be called from constant contexts" } +} diff --git a/gcc/testsuite/rust/compile/const_generics_1.rs b/gcc/testsuite/rust/compile/const_generics_1.rs new file mode 100644 index 00000000000..bcad8ee6a19 --- /dev/null +++ b/gcc/testsuite/rust/compile/const_generics_1.rs @@ -0,0 +1,19 @@ +// { dg-additional-options "-w" } + +// There are errors about unused generic parameters, but we can't handle that yet. +// Still, this code is invalid Rust. + +mod sain { + struct Foo; + struct Bar; + struct Baz<'l, T, const N: usize>; +} + +mod doux { + struct Foo; + struct Bar; + + const N_DEFAULT: usize = 3; + + struct Baz<'l, T, const N: usize = N_DEFAULT>; +} diff --git a/gcc/testsuite/rust/compile/const_generics_2.rs b/gcc/testsuite/rust/compile/const_generics_2.rs new file mode 100644 index 00000000000..98495cf404d --- /dev/null +++ b/gcc/testsuite/rust/compile/const_generics_2.rs @@ -0,0 +1,4 @@ +struct Foo; // { dg-error "expecting .:. but .>. found" } +struct Bar; // { dg-error "unrecognised token .>. in type" } +struct Baz; // { dg-error "invalid token for start of default value for const generic parameter" } +// { dg-error "unrecognised token .>. in type" "" { target *-*-* } .-1 } diff --git a/gcc/testsuite/rust/compile/const_generics_3.rs b/gcc/testsuite/rust/compile/const_generics_3.rs new file mode 100644 index 00000000000..6a3a0fe27bf --- /dev/null +++ b/gcc/testsuite/rust/compile/const_generics_3.rs @@ -0,0 +1,26 @@ +// { dg-additional-options "-w" } + +const M: usize = 4; + +struct Foo { + // FIXME: This error is bogus. But having it means parsing is valid! + value: [i32; N], // { dg-error "failed to find name: N" } +} + +fn main() { + let foo = Foo:: { value: [15] }; + let foo = Foo:: { value: [15, 13] }; + let foo: Foo = Foo { value: [15, 13] }; + let foo: Foo = Foo:: { value: [15, 13] }; + let foo: Foo = Foo { value: [15, 13] }; + let foo = Foo:: { value: [15, 13] }; + let foo: Foo = Foo:: { value: [15, 13] }; + let foo: Foo = Foo:: { + value: [15, 13, 11, 9], + }; + + // FIXME: Add proper const typecheck errors here + let invalid_foo: Foo = Foo:: { value: [15, 13] }; + let invalid_foo: Foo = Foo:: { value: [15, 13] }; + let invalid_foo: Foo = Foo:: { value: [15, 13] }; +} diff --git a/gcc/testsuite/rust/compile/const_generics_4.rs b/gcc/testsuite/rust/compile/const_generics_4.rs new file mode 100644 index 00000000000..8a3754da433 --- /dev/null +++ b/gcc/testsuite/rust/compile/const_generics_4.rs @@ -0,0 +1,7 @@ +// { dg-additional-options "-w" } + +const P: usize = 14; + +struct Foo; // { dg-error "failed to find name: M" } +struct Bar; +struct Baz; // { dg-error "failed to resolve TypePath: NotAType in this scope" } diff --git a/gcc/testsuite/rust/compile/const_generics_5.rs b/gcc/testsuite/rust/compile/const_generics_5.rs new file mode 100644 index 00000000000..5344e31a140 --- /dev/null +++ b/gcc/testsuite/rust/compile/const_generics_5.rs @@ -0,0 +1,12 @@ +struct Foo; + +const M: usize = 15; +type N = Foo<3>; + +fn main() { + let _: Foo<15> = Foo; + let _: Foo<{ M }> = Foo; + let _: Foo = Foo; + // bogus error, but it means the above const generic gets disambiguated properly + let _: Foo = Foo; // { dg-error "TypePath Foo declares generic arguments but the type Foo{Foo {}} does not have any" } +} diff --git a/gcc/testsuite/rust/compile/const_generics_6.rs b/gcc/testsuite/rust/compile/const_generics_6.rs new file mode 100644 index 00000000000..de261236d93 --- /dev/null +++ b/gcc/testsuite/rust/compile/const_generics_6.rs @@ -0,0 +1,2 @@ +struct Foo; +struct Bar; // { dg-error "expected .usize. got .i32." } diff --git a/gcc/testsuite/rust/compile/continue1.rs b/gcc/testsuite/rust/compile/continue1.rs new file mode 100644 index 00000000000..994312b52cc --- /dev/null +++ b/gcc/testsuite/rust/compile/continue1.rs @@ -0,0 +1,10 @@ +fn main() { + let mut a = 1; + let mut b = 1; + + let _fib = { + continue; // { dg-error "cannot 'continue' outside of a loop" } + // { dg-error "failed to type resolve expression" "" { target *-*-* } .-1 } + 123 + }; +} diff --git a/gcc/testsuite/rust/compile/deadcode_err1.rs b/gcc/testsuite/rust/compile/deadcode_err1.rs new file mode 100644 index 00000000000..1dbe95731e1 --- /dev/null +++ b/gcc/testsuite/rust/compile/deadcode_err1.rs @@ -0,0 +1,11 @@ +fn foo() -> i32 { + return 1; + + let mut a = 1; // { dg-warning "unreachable statement" } + a = 1.1; // { dg-warning "unreachable statement" } + // { dg-error "expected .. got .." "" { target *-*-* } .-1 } +} + +fn main() { + foo(); +} diff --git a/gcc/testsuite/rust/compile/deadcode_err2.rs b/gcc/testsuite/rust/compile/deadcode_err2.rs new file mode 100644 index 00000000000..8c0eb4617a7 --- /dev/null +++ b/gcc/testsuite/rust/compile/deadcode_err2.rs @@ -0,0 +1,16 @@ +fn foo() -> i32 { + return 1; + return 1.5; // { dg-error "expected .i32. got .." } + // { dg-warning "unreachable statement" "" { target *-*-* } .-1 } +} + +fn bar() -> i32 { + return 1.5; // { dg-error "expected .i32. got .." } + return 1; + // { dg-warning "unreachable statement" "" { target *-*-* } .-1 } +} + +fn main() { + foo(); + bar(); +} diff --git a/gcc/testsuite/rust/compile/debug-diagnostics-default.rs b/gcc/testsuite/rust/compile/debug-diagnostics-default.rs new file mode 100644 index 00000000000..90b0e575b45 --- /dev/null +++ b/gcc/testsuite/rust/compile/debug-diagnostics-default.rs @@ -0,0 +1,5 @@ +// Make sure we don't see any 'note's: +// { dg-bogus {note: } "" { target *-*-* } 0 } + +fn main() { +} diff --git a/gcc/testsuite/rust/compile/debug-diagnostics-off.rs b/gcc/testsuite/rust/compile/debug-diagnostics-off.rs new file mode 100644 index 00000000000..77b82b35e62 --- /dev/null +++ b/gcc/testsuite/rust/compile/debug-diagnostics-off.rs @@ -0,0 +1,7 @@ +// { dg-additional-options "-fno-rust-debug" } + +// Make sure we don't see any 'note's: +// { dg-bogus {note: } "" { target *-*-* } 0 } + +fn main() { +} diff --git a/gcc/testsuite/rust/compile/debug-diagnostics-on.rs b/gcc/testsuite/rust/compile/debug-diagnostics-on.rs new file mode 100644 index 00000000000..847fd24d7bd --- /dev/null +++ b/gcc/testsuite/rust/compile/debug-diagnostics-on.rs @@ -0,0 +1,7 @@ +// { dg-additional-options "-frust-debug" } + +// Just scan for one of the Rust front end debug diagnostics: +// { dg-message {note: Attempting to parse file: .+/gcc/testsuite/rust/compile/debug-diagnostics-on\.rs} "" { target *-*-* } 0 } + +fn main() { +} diff --git a/gcc/testsuite/rust/compile/doc_isolated_cr_block_comment.rs b/gcc/testsuite/rust/compile/doc_isolated_cr_block_comment.rs new file mode 100644 index 00000000000..0ada77f69cf --- /dev/null +++ b/gcc/testsuite/rust/compile/doc_isolated_cr_block_comment.rs @@ -0,0 +1,3 @@ +// { dg-error "Isolated CR" "" { target *-*-* } .+1 } +/** doc cr comment */ +pub fn main () { } diff --git a/gcc/testsuite/rust/compile/doc_isolated_cr_inner_block_comment.rs b/gcc/testsuite/rust/compile/doc_isolated_cr_inner_block_comment.rs new file mode 100644 index 00000000000..7db35341bee --- /dev/null +++ b/gcc/testsuite/rust/compile/doc_isolated_cr_inner_block_comment.rs @@ -0,0 +1,5 @@ +pub fn main () +{ +// { dg-error "Isolated CR" "" { target *-*-* } .+1 } + /*! doc cr comment */ +} diff --git a/gcc/testsuite/rust/compile/doc_isolated_cr_inner_line_comment.rs b/gcc/testsuite/rust/compile/doc_isolated_cr_inner_line_comment.rs new file mode 100644 index 00000000000..d75da75e218 --- /dev/null +++ b/gcc/testsuite/rust/compile/doc_isolated_cr_inner_line_comment.rs @@ -0,0 +1,5 @@ +pub fn main () +{ +// { dg-error "Isolated CR" "" { target *-*-* } .+1 } + //! doc cr comment +} diff --git a/gcc/testsuite/rust/compile/doc_isolated_cr_line_comment.rs b/gcc/testsuite/rust/compile/doc_isolated_cr_line_comment.rs new file mode 100644 index 00000000000..7b6ef989c30 --- /dev/null +++ b/gcc/testsuite/rust/compile/doc_isolated_cr_line_comment.rs @@ -0,0 +1,3 @@ +// { dg-error "Isolated CR" "" { target *-*-* } .+1 } +/// doc cr comment +pub fn main () { } diff --git a/gcc/testsuite/rust/compile/dup_fields.rs b/gcc/testsuite/rust/compile/dup_fields.rs new file mode 100644 index 00000000000..ab39955eca0 --- /dev/null +++ b/gcc/testsuite/rust/compile/dup_fields.rs @@ -0,0 +1,23 @@ +struct S { a: i32, b: i32, c: u8, a: i128 } +// { dg-error "duplicate field" "" { target *-*-* } .-1 } + +union U + { + a: i32, + b: i32, + c: u8, + b: char // { dg-error "duplicate field" "" { target *-*-* } } + } + +fn main () +{ + struct SS { alpha: i32, beta: i32, gamma: u8, gamma: i128 } + // { dg-error "duplicate field" "" { target *-*-* } .-1 } + + union UU + { + alpha: i32, beta: i32, + gamma: u8, beta: char + // { dg-error "duplicate field" "" { target *-*-* } .-1 } + } +} diff --git a/gcc/testsuite/rust/compile/empty_comment_before_match.rs b/gcc/testsuite/rust/compile/empty_comment_before_match.rs new file mode 100644 index 00000000000..3d344d3e758 --- /dev/null +++ b/gcc/testsuite/rust/compile/empty_comment_before_match.rs @@ -0,0 +1,7 @@ +fn foo (x: i8) -> i32 { // { dg-warning "function is never used" } + // + match x { + 1 => { return 1; } + _ => { return 0; } + } +} diff --git a/gcc/testsuite/rust/compile/expected_type_args2.rs b/gcc/testsuite/rust/compile/expected_type_args2.rs new file mode 100644 index 00000000000..79454202aad --- /dev/null +++ b/gcc/testsuite/rust/compile/expected_type_args2.rs @@ -0,0 +1,6 @@ +struct Foo(A); + +fn main() { + let a: Foo = Foo::(123); + // { dg-error "generic item takes at least 1 type arguments but 0 were supplied" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/expected_type_args3.rs b/gcc/testsuite/rust/compile/expected_type_args3.rs new file mode 100644 index 00000000000..ba07239207a --- /dev/null +++ b/gcc/testsuite/rust/compile/expected_type_args3.rs @@ -0,0 +1,8 @@ +struct Foo(A); + +impl Foo { + // { dg-error "generic item takes at least 1 type arguments but 0 were supplied" "" { target *-*-* } .-1 } + fn test() -> i32 { + 123 + } +} diff --git a/gcc/testsuite/rust/compile/func1.rs b/gcc/testsuite/rust/compile/func1.rs new file mode 100644 index 00000000000..6758a3898e3 --- /dev/null +++ b/gcc/testsuite/rust/compile/func1.rs @@ -0,0 +1,9 @@ +fn test(x: i32) -> bool { + return x + 1; // { dg-error "expected .bool. got .i32." } +} + +fn main() { + let an_integer = 5; + + let call_test = test(1); +} diff --git a/gcc/testsuite/rust/compile/func2.rs b/gcc/testsuite/rust/compile/func2.rs new file mode 100644 index 00000000000..0b8d999fec1 --- /dev/null +++ b/gcc/testsuite/rust/compile/func2.rs @@ -0,0 +1,7 @@ +fn test(a: i32, b: i32) -> i32 { + a + b +} + +fn main() { + let a = test(1); // { dg-error "unexpected number of arguments 1 expected 2" } +} diff --git a/gcc/testsuite/rust/compile/func3.rs b/gcc/testsuite/rust/compile/func3.rs new file mode 100644 index 00000000000..2a329476118 --- /dev/null +++ b/gcc/testsuite/rust/compile/func3.rs @@ -0,0 +1,9 @@ +fn test(a: i32, b: i32) -> i32 { + a + b +} + +fn main() { + let a = test(1, true); + // { dg-error "expected .i32. got .bool." "" { target *-*-* } .-1 } + // { dg-error "Type Resolution failure on parameter" "" { target *-*-* } .-2 } +} diff --git a/gcc/testsuite/rust/compile/func4.rs b/gcc/testsuite/rust/compile/func4.rs new file mode 100644 index 00000000000..3b2d2b0d773 --- /dev/null +++ b/gcc/testsuite/rust/compile/func4.rs @@ -0,0 +1,6 @@ +fn func() -> i32 { // { dg-error "expected .i32. got ...." } +} + +fn main() { + func(); +} diff --git a/gcc/testsuite/rust/compile/func5.rs b/gcc/testsuite/rust/compile/func5.rs new file mode 100644 index 00000000000..05624f524e9 --- /dev/null +++ b/gcc/testsuite/rust/compile/func5.rs @@ -0,0 +1,7 @@ +fn func() -> i32 { + return; // { dg-error "expected .i32. got ...." } +} + +fn main() { + func(); +} diff --git a/gcc/testsuite/rust/compile/generic-default1.rs b/gcc/testsuite/rust/compile/generic-default1.rs new file mode 100644 index 00000000000..0a132bf5d6b --- /dev/null +++ b/gcc/testsuite/rust/compile/generic-default1.rs @@ -0,0 +1,7 @@ +struct Foo(A); +// { dg-error "failed to resolve TypePath: i321" "" { target *-*-* } .-1 } + +fn main() { + let a; + a = Foo(123); +} diff --git a/gcc/testsuite/rust/compile/generics1.rs b/gcc/testsuite/rust/compile/generics1.rs new file mode 100644 index 00000000000..de1bbf5dafb --- /dev/null +++ b/gcc/testsuite/rust/compile/generics1.rs @@ -0,0 +1,11 @@ +// { dg-error "expected .i32. got .i8." "" { target *-*-* } 0 } + +struct GenericStruct(T, usize); + +fn main() { + let a2: GenericStruct; + a2 = GenericStruct::<_>(1, 456); + + let b2: i32 = a2.0; + let c2: usize = a2.1; +} diff --git a/gcc/testsuite/rust/compile/generics10.rs b/gcc/testsuite/rust/compile/generics10.rs new file mode 100644 index 00000000000..a734fa8a197 --- /dev/null +++ b/gcc/testsuite/rust/compile/generics10.rs @@ -0,0 +1,12 @@ +struct Foo(A, B); + +impl Foo { // { dg-error "defaults for type parameters are not allowed here" } + fn new(a: X, b: f32) -> Self { + Self(a, b) + } +} + +fn main() { + let a; + a = Foo::new(123, 456f32); +} diff --git a/gcc/testsuite/rust/compile/generics11.rs b/gcc/testsuite/rust/compile/generics11.rs new file mode 100644 index 00000000000..4d3b9e1777c --- /dev/null +++ b/gcc/testsuite/rust/compile/generics11.rs @@ -0,0 +1,12 @@ +struct Foo(T, bool); + +impl Foo { + fn test() -> i32 { + 123 + } +} + +fn main() { + let a = Foo::test(); + // { dg-error "type annotations needed" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/generics12.rs b/gcc/testsuite/rust/compile/generics12.rs new file mode 100644 index 00000000000..f1ac8b0314b --- /dev/null +++ b/gcc/testsuite/rust/compile/generics12.rs @@ -0,0 +1,6 @@ +fn main() { + bar(); + // { dg-error "type annotations needed" "" { target *-*-* } .-1 } +} + +fn bar() {} diff --git a/gcc/testsuite/rust/compile/generics13.rs b/gcc/testsuite/rust/compile/generics13.rs new file mode 100644 index 00000000000..05c75c5f63d --- /dev/null +++ b/gcc/testsuite/rust/compile/generics13.rs @@ -0,0 +1 @@ +struct Foo; // { dg-error "invalid order for generic parameters: lifetimes should always come before types" } diff --git a/gcc/testsuite/rust/compile/generics2.rs b/gcc/testsuite/rust/compile/generics2.rs new file mode 100644 index 00000000000..5812b133038 --- /dev/null +++ b/gcc/testsuite/rust/compile/generics2.rs @@ -0,0 +1,11 @@ +// { dg-error "expected .i32. got .i8." "" { target *-*-* } 0 } + +struct GenericStruct(T, usize); + +fn main() { + let a2: GenericStruct; + a2 = GenericStruct(1, 456); + + let b2: i32 = a2.0; + let c2: usize = a2.1; +} diff --git a/gcc/testsuite/rust/compile/generics3.rs b/gcc/testsuite/rust/compile/generics3.rs new file mode 100644 index 00000000000..2d4210588fb --- /dev/null +++ b/gcc/testsuite/rust/compile/generics3.rs @@ -0,0 +1,10 @@ +// { dg-error "expected .i32. got .i8." "" { target *-*-* } 0 } +struct GenericStruct(T, usize); + +fn main() { + let a2; + a2 = GenericStruct::(1, 456); + + let b2: i32 = a2.0; + let c2: usize = a2.1; +} diff --git a/gcc/testsuite/rust/compile/generics4.rs b/gcc/testsuite/rust/compile/generics4.rs new file mode 100644 index 00000000000..8af13586a37 --- /dev/null +++ b/gcc/testsuite/rust/compile/generics4.rs @@ -0,0 +1,16 @@ +struct GenericStruct(T, usize); + +fn main() { + let a2; + a2 = GenericStruct::(1, 456); // { dg-error "generic item takes at most 1 type arguments but 2 were supplied" } + // { dg-error {failed to type resolve expression} "" { target *-*-* } .-1 } + // { dg-error {Failed to resolve expression of function call} "" { target *-*-* } .-2 } + // { duplicate _dg-error {failed to type resolve expression} "" { target *-*-* } .-3 } + + let b2: i32 = a2.0; + // { dg-error {Expected Tuple or ADT got: T\?} "" { target *-*-* } .-1 } + // { dg-error {failed to type resolve expression} "" { target *-*-* } .-2 } + let c2: usize = a2.1; + // { dg-error {Expected Tuple or ADT got: T\?} "" { target *-*-* } .-1 } + // { dg-error {failed to type resolve expression} "" { target *-*-* } .-2 } +} diff --git a/gcc/testsuite/rust/compile/generics5.rs b/gcc/testsuite/rust/compile/generics5.rs new file mode 100644 index 00000000000..6c847b5a29b --- /dev/null +++ b/gcc/testsuite/rust/compile/generics5.rs @@ -0,0 +1,10 @@ +struct GenericStruct(T, usize); + +fn main() { + let a2; + a2 = GenericStruct::(1, 456); + // { dg-error "failed to resolve TypePath: T" "" { target *-*-* } .-1 } + + let b2: i32 = a2.0; + let c2: usize = a2.1; +} diff --git a/gcc/testsuite/rust/compile/generics6.rs b/gcc/testsuite/rust/compile/generics6.rs new file mode 100644 index 00000000000..3b81e1bbee1 --- /dev/null +++ b/gcc/testsuite/rust/compile/generics6.rs @@ -0,0 +1,31 @@ +struct Foo { + a: A, +} + +impl Foo { + fn test() -> i32 { // { dg-error "possible candidate" "TODO" { xfail *-*-* } } + 123 + } + + fn bar(self) -> isize { + self.a + } +} + +impl Foo { + fn test() -> i32 { // { dg-error "possible candidate" "TODO" { xfail *-*-* } } + 123 + } + + fn bar(self) -> f32 { + self.a + } +} + +fn main() { + let a: i32 = Foo::test(); // { dg-error "multiple applicable items in scope for: test" } + // { dg-error {failed to type resolve expression} "" { target *-*-* } .-1 } + // { dg-error {Failed to resolve expression of function call} "" { target *-*-* } .-2 } + // { duplicate _dg-error {failed to type resolve expression} "" { target *-*-* } .-3 } +} + diff --git a/gcc/testsuite/rust/compile/generics7.rs b/gcc/testsuite/rust/compile/generics7.rs new file mode 100644 index 00000000000..2a41632e693 --- /dev/null +++ b/gcc/testsuite/rust/compile/generics7.rs @@ -0,0 +1,26 @@ +struct Foo { + a: A, +} + +impl Foo { + fn bar(self) -> isize { // { dg-error "duplicate definitions with name bar" } + self.a + } +} + +impl Foo { + fn bar(self) -> char { // { dg-error "duplicate definitions with name bar" } + self.a + } +} + +impl Foo { + fn bar(self) -> T { + self.a + } +} + +fn main() { + let a = Foo { a: 123 }; + a.bar(); +} diff --git a/gcc/testsuite/rust/compile/generics8.rs b/gcc/testsuite/rust/compile/generics8.rs new file mode 100644 index 00000000000..ceefc5d2c6a --- /dev/null +++ b/gcc/testsuite/rust/compile/generics8.rs @@ -0,0 +1,15 @@ +struct Foo(A, B); + +impl Foo { + fn test(a: T) -> T { + a + } +} + +impl Foo { + fn test() -> f32 { // { dg-error "duplicate definitions with name test" } + 123f32 + } +} + +fn main() {} diff --git a/gcc/testsuite/rust/compile/generics9.rs b/gcc/testsuite/rust/compile/generics9.rs new file mode 100644 index 00000000000..3766703431e --- /dev/null +++ b/gcc/testsuite/rust/compile/generics9.rs @@ -0,0 +1,10 @@ +struct Foo(A, B); +// { dg-error "failed to resolve TypePath: B" "" { target *-*-* } .-1 } + +fn main() { + let a: Foo; + a = Foo::(true, (false, true)); + + let b: (bool, bool); + b = a.1; +} diff --git a/gcc/testsuite/rust/compile/implicit_returns_err1.rs b/gcc/testsuite/rust/compile/implicit_returns_err1.rs new file mode 100644 index 00000000000..973ba80fb86 --- /dev/null +++ b/gcc/testsuite/rust/compile/implicit_returns_err1.rs @@ -0,0 +1,12 @@ +fn test(x: i32) -> i32 { + if x > 1 { // { dg-error "expected .... got .." } + 1 + } else { + 2 + } + 3 +} + +fn main() { + let a = test(1); +} diff --git a/gcc/testsuite/rust/compile/implicit_returns_err2.rs b/gcc/testsuite/rust/compile/implicit_returns_err2.rs new file mode 100644 index 00000000000..fb90748871f --- /dev/null +++ b/gcc/testsuite/rust/compile/implicit_returns_err2.rs @@ -0,0 +1,10 @@ +fn test(x: i32) -> i32 { + // { dg-error "expected .i32. got .bool." "" { target *-*-* } .-1 } + return 1; + // { dg-warning "unreachable expression" "" { target *-*-* } .+1 } + true +} + +fn main() { + let a = test(1); +} diff --git a/gcc/testsuite/rust/compile/implicit_returns_err3.rs b/gcc/testsuite/rust/compile/implicit_returns_err3.rs new file mode 100644 index 00000000000..37b1c62414c --- /dev/null +++ b/gcc/testsuite/rust/compile/implicit_returns_err3.rs @@ -0,0 +1,9 @@ +fn test(x: i32) -> i32 { // { dg-error "expected .i32. got ...." } + if x > 1 { + 1 + } +} + +fn main() { + let a = test(9); +} diff --git a/gcc/testsuite/rust/compile/implicit_returns_err4.rs b/gcc/testsuite/rust/compile/implicit_returns_err4.rs new file mode 100644 index 00000000000..59c6a020d4c --- /dev/null +++ b/gcc/testsuite/rust/compile/implicit_returns_err4.rs @@ -0,0 +1,10 @@ +fn test(x: bool) -> bool { + // { dg-error "expected .bool. got ...." "" { target *-*-*} .-1 } + return x; + // { dg-warning "unreachable expression" "" { target *-*-* } .+1 } + () +} + +fn main() { + let a = test(true); +} diff --git a/gcc/testsuite/rust/compile/infer-crate-name.rs b/gcc/testsuite/rust/compile/infer-crate-name.rs new file mode 100644 index 00000000000..b0c0086c04c --- /dev/null +++ b/gcc/testsuite/rust/compile/infer-crate-name.rs @@ -0,0 +1,7 @@ +// { dg-additional-options "-fdump-tree-gimple" } +pub fn does_nothing() {} +fn main() { + does_nothing() +} +// { dg-final { scan-tree-dump-times {infer_crate_name::does_nothing} 2 gimple } } +// { dg-final { scan-tree-dump-times {infer_crate_name::main} 1 gimple } } diff --git a/gcc/testsuite/rust/compile/inline_1.rs b/gcc/testsuite/rust/compile/inline_1.rs new file mode 100644 index 00000000000..4b0f991765a --- /dev/null +++ b/gcc/testsuite/rust/compile/inline_1.rs @@ -0,0 +1,16 @@ +// { dg-additional-options "-fdump-tree-gimple" } +#[inline] +fn test_a() {} + +// { dg-final { scan-tree-dump-times {always_inline} 1 gimple } } +#[inline(always)] +fn test_b() {} + +#[inline(never)] +fn test_c() {} + +fn main() { + test_a(); + test_b(); + test_c(); +} diff --git a/gcc/testsuite/rust/compile/inline_2.rs b/gcc/testsuite/rust/compile/inline_2.rs new file mode 100644 index 00000000000..3665fdac804 --- /dev/null +++ b/gcc/testsuite/rust/compile/inline_2.rs @@ -0,0 +1,6 @@ +// { dg-additional-options "-w" } +#[inline(A)] // { dg-error "unknown inline option" } +fn test_a() {} + +#[inline(A, B)] // { dg-error "invalid number of arguments" } +fn test_b() {} diff --git a/gcc/testsuite/rust/compile/issue-1005.rs b/gcc/testsuite/rust/compile/issue-1005.rs new file mode 100644 index 00000000000..46c85eea91e --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1005.rs @@ -0,0 +1,4 @@ +// { dg-additional-options "-w" } +impl *const T { + fn test(self) {} +} diff --git a/gcc/testsuite/rust/compile/issue-1019.rs b/gcc/testsuite/rust/compile/issue-1019.rs new file mode 100644 index 00000000000..aea86a821c7 --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1019.rs @@ -0,0 +1,19 @@ +trait A { + type Output; + + fn test(self, a: &T) -> &Self::Output; +} + +struct Foo { + // { dg-warning "struct is never constructed" "" { target *-*-* } .-1 } + start: T, + end: T, +} + +impl A for Foo { + type Output = X; + + fn test(self, a: &X) -> &Self::Output { + a + } +} diff --git a/gcc/testsuite/rust/compile/issue-1023.rs b/gcc/testsuite/rust/compile/issue-1023.rs new file mode 100644 index 00000000000..5a0fe6cf530 --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1023.rs @@ -0,0 +1,4 @@ +// { dg-additional-options "-w" } +fn foo(e: &str) -> &str { + &"" +} diff --git a/gcc/testsuite/rust/compile/issue-1031.rs b/gcc/testsuite/rust/compile/issue-1031.rs new file mode 100644 index 00000000000..939f0f981e0 --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1031.rs @@ -0,0 +1,17 @@ +extern "rust-intrinsic" { + #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")] + pub fn offset(dst: *const T, offset: isize) -> *const T; +} + +#[lang = "const_ptr"] +impl *const T { + pub const unsafe fn offset(self, count: isize) -> *const T { + // { dg-warning "associated function is never used" "" { target *-*-* } .-1 } + unsafe { offset(self, count) } + } + + pub const unsafe fn add(self, count: usize) -> Self { + // { dg-warning "associated function is never used" "" { target *-*-* } .-1 } + unsafe { self.offset(count as isize) } + } +} diff --git a/gcc/testsuite/rust/compile/issue-1034.rs b/gcc/testsuite/rust/compile/issue-1034.rs new file mode 100644 index 00000000000..23d77005452 --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1034.rs @@ -0,0 +1,16 @@ +trait Foo { + type Output; + + fn test(self, slice: &T) -> &Self::Output; +} + +struct Bar(T); +// { dg-warning "struct is never constructed" "" { target *-*-* } .-1 } + +impl Foo<[T]> for Bar { + type Output = [T]; + + fn test(self, slice: &[T]) -> &[T] { + slice + } +} diff --git a/gcc/testsuite/rust/compile/issue-1089.rs b/gcc/testsuite/rust/compile/issue-1089.rs new file mode 100644 index 00000000000..635af293dbb --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1089.rs @@ -0,0 +1,6 @@ +// { dg-additional-options "-w" } +pub mod test_mod; + +fn main() { + let a = test_mod::Test(123); +} diff --git a/gcc/testsuite/rust/compile/issue-1128.rs b/gcc/testsuite/rust/compile/issue-1128.rs new file mode 100644 index 00000000000..462426b679d --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1128.rs @@ -0,0 +1,6 @@ +pub trait Hasher { + fn write(&mut self, bytes: &[u8]); + fn write_u8(&mut self, i: u8) { + self.write(&[i]) + } +} diff --git a/gcc/testsuite/rust/compile/issue-1129-1.rs b/gcc/testsuite/rust/compile/issue-1129-1.rs new file mode 100644 index 00000000000..a15903983f0 --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1129-1.rs @@ -0,0 +1,4 @@ +// { dg-additional-options "-w" } +fn write_u8(i: u8) { + let x: &[u8] = &[i]; +} diff --git a/gcc/testsuite/rust/compile/issue-1129-2.rs b/gcc/testsuite/rust/compile/issue-1129-2.rs new file mode 100644 index 00000000000..25d30faf4aa --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1129-2.rs @@ -0,0 +1,22 @@ +// { dg-additional-options "-w" } +pub trait Hasher { + fn finish(&self) -> u64; + fn write(&mut self, bytes: &[u8]); + fn write_u8(&mut self, i: u8) { + self.write(&[i]) + } +} + +struct SipHasher; + +impl Hasher for SipHasher { + #[inline] + fn write(&mut self, msg: &[u8]) { + loop {} + } + + #[inline] + fn finish(&self) -> u64 { + 0 + } +} diff --git a/gcc/testsuite/rust/compile/issue-1130.rs b/gcc/testsuite/rust/compile/issue-1130.rs new file mode 100644 index 00000000000..92200c7cd5f --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1130.rs @@ -0,0 +1,47 @@ +// { dg-additional-options "-w" } +mod mem { + extern "rust-intrinsic" { + fn size_of() -> usize; + fn transmute(_: U) -> V; + } +} + +impl u16 { + fn to_ne_bytes(self) -> [u8; mem::size_of::()] { + unsafe { mem::transmute(self) } + } +} + +pub trait Hasher { + fn finish(&self) -> u64; + + fn write(&mut self, bytes: &[u8]); + + fn write_u8(&mut self, i: u8) { + self.write(&[i]) + } + + fn write_i8(&mut self, i: i8) { + self.write_u8(i as u8) + } + + fn write_u16(&mut self, i: u16) { + self.write(&i.to_ne_bytes()) + } + + fn write_i16(&mut self, i: i16) { + self.write_u16(i as u16) + } +} + +pub struct SipHasher; + +impl Hasher for SipHasher { + #[inline] + fn write(&mut self, msg: &[u8]) {} + + #[inline] + fn finish(&self) -> u64 { + 0 + } +} diff --git a/gcc/testsuite/rust/compile/issue-1131.rs b/gcc/testsuite/rust/compile/issue-1131.rs new file mode 100644 index 00000000000..fd158abc700 --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1131.rs @@ -0,0 +1,4 @@ +extern "rust-intrinsic" { + fn size_of() -> usize; + fn offset(dst: *const T, offset: isize) -> *const T; +} diff --git a/gcc/testsuite/rust/compile/issue-1152.rs b/gcc/testsuite/rust/compile/issue-1152.rs new file mode 100644 index 00000000000..18eee9e6b4a --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1152.rs @@ -0,0 +1,8 @@ +fn test() { + let f = [0; -4_isize]; + // { dg-error "expected .usize. got .isize." "" { target *-*-* } .-1 } + // { dg-error "failed to type resolve expression" "" { target *-*-* } .-2 } + let f = [0_usize; -1_isize]; + // { dg-error "expected .usize. got .isize." "" { target *-*-* } .-1 } + // { dg-error "failed to type resolve expression" "" { target *-*-* } .-2 } +} diff --git a/gcc/testsuite/rust/compile/issue-1165.rs b/gcc/testsuite/rust/compile/issue-1165.rs new file mode 100644 index 00000000000..f5889698d70 --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1165.rs @@ -0,0 +1,5 @@ +struct Foo(T); + +fn main() { + &Foo(123); +} diff --git a/gcc/testsuite/rust/compile/issue-1173.rs b/gcc/testsuite/rust/compile/issue-1173.rs new file mode 100644 index 00000000000..5c2a9173241 --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1173.rs @@ -0,0 +1,23 @@ +// { dg-additional-options "-w" } + +#![feature(intrinsics)] + +mod mem { + extern "rust-intrinsic" { + pub fn transmute(_: U) -> V; + } +} + +pub trait Hasher { + fn write(&mut self, bytes: &[u8]); + fn write_u16(&mut self, i: u16) { + self.write(unsafe { &mem::transmute::<_, [u8; 2]>(i) }) + } +} + +pub struct SipHasher; + +impl Hasher for SipHasher { + #[inline] + fn write(&mut self, msg: &[u8]) {} +} diff --git a/gcc/testsuite/rust/compile/issue-1226.rs b/gcc/testsuite/rust/compile/issue-1226.rs new file mode 100644 index 00000000000..f5f9e5ff08d --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1226.rs @@ -0,0 +1,6 @@ +// { dg-additional-options "-w" } +const TEST: *mut u8 = 123 as *mut u8; + +fn test() { + let a = TEST; +} diff --git a/gcc/testsuite/rust/compile/issue-1234.rs b/gcc/testsuite/rust/compile/issue-1234.rs new file mode 100644 index 00000000000..c6d5932c004 --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1234.rs @@ -0,0 +1,4 @@ +fn foo() -> u8 { + // { dg-warning "function is never used" "" { target *-*-* } .-1 } + 1u8 << 2u32 +} diff --git a/gcc/testsuite/rust/compile/issue-1235.rs b/gcc/testsuite/rust/compile/issue-1235.rs new file mode 100644 index 00000000000..098b337455f --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1235.rs @@ -0,0 +1,21 @@ +// { dg-additional-options "-w" } +struct FatPtr { + data: *const T, + len: usize, +} + +pub union Repr { + rust: *const [T], + rust_mut: *mut [T], + raw: FatPtr, +} + +impl [T] { + pub const fn is_empty(&self) -> bool { + self.len() == 0 + } + + pub const fn len(&self) -> usize { + unsafe { Repr { rust: self }.raw.len } + } +} diff --git a/gcc/testsuite/rust/compile/issue-1237.rs b/gcc/testsuite/rust/compile/issue-1237.rs new file mode 100644 index 00000000000..542be897949 --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1237.rs @@ -0,0 +1,23 @@ +// { dg-additional-options "-w" } +mod intrinsics { + extern "rust-intrinsic" { + pub fn offset(ptr: *const T, count: isize) -> *const T; + } +} + +impl *const T { + pub unsafe fn offset(self, count: isize) -> *const T { + unsafe { intrinsics::offset(self, count) } + } +} + +impl [T] { + pub unsafe fn get_unchecked(&self, index: usize) -> &T { + unsafe { &*(self as *const [T] as *const T).offset(index as isize) } + } +} + +#[inline] +unsafe fn u8to64_le(buf: &[u8], start: usize, len: usize) -> u64 { + (unsafe { *buf.get_unchecked(start) } as u64) +} diff --git a/gcc/testsuite/rust/compile/issue-1251.rs b/gcc/testsuite/rust/compile/issue-1251.rs new file mode 100644 index 00000000000..b16e1e0b0d9 --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1251.rs @@ -0,0 +1,14 @@ +// { dg-additional-options "-w" } +mod a { + pub mod b { + pub mod a { + pub fn foo() {} + } + } + + pub fn bidule() { + crate::a::b::a::foo() + } +} + +fn main() {} diff --git a/gcc/testsuite/rust/compile/issue-1271.rs b/gcc/testsuite/rust/compile/issue-1271.rs new file mode 100644 index 00000000000..5dd6418de4c --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1271.rs @@ -0,0 +1,5 @@ +// { dg-additional-options "-w" } +fn test() { + let a: &str = "TEST 1"; + let b: &str = &"TEST 2"; +} diff --git a/gcc/testsuite/rust/compile/issue-1289.rs b/gcc/testsuite/rust/compile/issue-1289.rs new file mode 100644 index 00000000000..343aaab078b --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1289.rs @@ -0,0 +1,43 @@ +extern "C" { + fn printf(s: *const i8, ...); +} + +mod intrinsics { + extern "rust-intrinsic" { + #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")] + pub fn offset(dst: *const T, offset: isize) -> *const T; + } +} + +#[lang = "mut_ptr"] +impl *mut T { + pub const unsafe fn offset(self, count: isize) -> *mut T { + unsafe { intrinsics::offset(self, count) as *mut T } + } + + pub const unsafe fn add(self, count: usize) -> Self { + unsafe { self.offset(count as isize) } + } +} + +#[lang = "const_ptr"] +impl *const T { + pub const unsafe fn offset(self, count: isize) -> *mut T { + // { dg-warning "associated function is never used" "" { target *-*-* } .-1 } + unsafe { intrinsics::offset(self, count) as *mut T } + } + + pub const unsafe fn add(self, count: usize) -> Self { + // { dg-warning "associated function is never used" "" { target *-*-* } .-1 } + unsafe { self.offset(count as isize) } + } +} + +fn main() -> i32 { + let a: *mut _ = &mut 123; + unsafe { + let _b = a.add(123); + } + + 0 +} diff --git a/gcc/testsuite/rust/compile/issue-1323-1.rs b/gcc/testsuite/rust/compile/issue-1323-1.rs new file mode 100644 index 00000000000..a6174253a21 --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1323-1.rs @@ -0,0 +1,18 @@ +fn main() { + let mut x = [1, 2, 3]; + let y: i32 = x[0]; + print_int(y); +} + +extern "C" { + fn printf(s: *const i8, ...); +} + +fn print_int(value: i32) { + let s = "%d\n\0"; + let s_p = s as *const str; + let c_p = s_p as *const i8; + unsafe { + printf(c_p, value as isize); + } +} diff --git a/gcc/testsuite/rust/compile/issue-1323-2.rs b/gcc/testsuite/rust/compile/issue-1323-2.rs new file mode 100644 index 00000000000..45168b22fa7 --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1323-2.rs @@ -0,0 +1,16 @@ +fn print_int(value: i32) { + let s = "%d\n\0"; + let s_p = s as *const str; + let c_p = s_p as *const i8; + unsafe { + printf(c_p, value as isize); + } +} + +fn main() { + print_int(5); +} + +extern "C" { + fn printf(s: *const i8, ...); +} diff --git a/gcc/testsuite/rust/compile/issue-1383.rs b/gcc/testsuite/rust/compile/issue-1383.rs new file mode 100644 index 00000000000..cca12e8fc71 --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1383.rs @@ -0,0 +1,8 @@ +pub fn generic_function(a: X) -> X { + a +} + +fn main() -> i32 { + let a = generic_function(123); + a - 123 +} diff --git a/gcc/testsuite/rust/compile/issue-1393.rs b/gcc/testsuite/rust/compile/issue-1393.rs new file mode 100644 index 00000000000..e09f01b62e5 --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1393.rs @@ -0,0 +1,13 @@ +fn tst() { + let a = 123; + let b = 0; + let _c = if b == 0 { + (a & 0x7fffff) << 1 + } else { + (a & 0x7fffff) | 0x800000 + }; +} + +fn main() { + tst() +} diff --git a/gcc/testsuite/rust/compile/issue-1447.rs b/gcc/testsuite/rust/compile/issue-1447.rs new file mode 100644 index 00000000000..e0543e6247c --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-1447.rs @@ -0,0 +1,28 @@ +// { dg-options "-w" } +struct PhantomData; + +struct Hasher { + _marker: PhantomData, +} + +struct Sip24Rounds; + +struct SipHasher24 { + hasher: Hasher, +} + +impl SipHasher24 { + pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher24 { + SipHasher24 { + hasher: Hasher::new_with_keys(), + } + } +} + +impl Hasher { + fn new_with_keys() -> Hasher { + Hasher { + _marker: PhantomData, + } + } +} diff --git a/gcc/testsuite/rust/compile/issue-407-2.rs b/gcc/testsuite/rust/compile/issue-407-2.rs new file mode 100644 index 00000000000..cb8027b9c7f --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-407-2.rs @@ -0,0 +1,21 @@ +// #407 +pub fn loopy() { + let mut a = 1; + // { dg-error {failed to parse expr with block in parsing expr statement} "" { target *-*-* } .+2 } + // { dg-error {failed to parse statement or expression without block in block expression} "" { target *-*-* } .+1 } + loop { + // { dg-error {failed to parse expr with block in parsing expr statement} "" { target *-*-* } .+2 } + // { dg-error {failed to parse statement or expression without block in block expression} "" { target *-*-* } .+1 } + if a < 40 { + a + = 1; // { dg-error "found unexpected token '=' in null denotation" } + // { dg-error {failed to parse expression for expression without block \(pratt-parsed expression is null\)} "" { target *-*-* } .-1 } + // { dg-error {failed to parse statement or expression without block in block expression} "" { target *-*-* } .-2 } + // { dg-error {failed to parse if body block expression in if expression} "" { target *-*-* } .-3 } + // { dg-error {could not parse loop body in \(infinite\) loop expression} "" { target *-*-* } .+1 } + } else { + break; + } + } +} +// { dg-error {unrecognised token '\}' for start of item} "" { target *-*-* } .-1 } +// { dg-error {failed to parse item in crate} "" { target *-*-* } .-2 } diff --git a/gcc/testsuite/rust/compile/issue-407.rs b/gcc/testsuite/rust/compile/issue-407.rs new file mode 100644 index 00000000000..530b7ddfc12 --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-407.rs @@ -0,0 +1,9 @@ +// This already worked before the #409 code changes. +fn test() { + let mut a = 1; + a + = 1; // { dg-error "found unexpected token '=' in null denotation" } + // { dg-error {failed to parse expression for expression without block \(pratt-parsed expression is null\)} "" { target *-*-* } .-1 } + // { dg-error {failed to parse statement or expression without block in block expression} "" { target *-*-* } .-2 } + // { dg-error {unrecognised token 'integer literal' for start of item} "" { target *-*-* } .-3 } + // { dg-error {failed to parse item in crate} "" { target *-*-* } .-4 } +} diff --git a/gcc/testsuite/rust/compile/issue-557.rs b/gcc/testsuite/rust/compile/issue-557.rs new file mode 100644 index 00000000000..aeb5ba6755b --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-557.rs @@ -0,0 +1,4 @@ +// { dg-additional-options "-w" } +fn test(a: i32, _: i32) { + let _ = 42 + a; +} diff --git a/gcc/testsuite/rust/compile/issue-635-1.rs b/gcc/testsuite/rust/compile/issue-635-1.rs new file mode 100644 index 00000000000..dc6a4c2eece --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-635-1.rs @@ -0,0 +1,5 @@ +// { dg-additional-options "-w" } +fn test() -> i32 { + return 10000000000000000000000000000000000000000000; + // { dg-error "integer overflows the respective type .i32." "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/issue-635-2.rs b/gcc/testsuite/rust/compile/issue-635-2.rs new file mode 100644 index 00000000000..335218aa52c --- /dev/null +++ b/gcc/testsuite/rust/compile/issue-635-2.rs @@ -0,0 +1,5 @@ +// { dg-additional-options "-w" } +fn test() -> f32 { + return 10000000000000000000000000000000000000000000.0f32; + // { dg-error "decimal overflows the respective type .f32." "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/lookup_err1.rs b/gcc/testsuite/rust/compile/lookup_err1.rs new file mode 100644 index 00000000000..4a96f9ff140 --- /dev/null +++ b/gcc/testsuite/rust/compile/lookup_err1.rs @@ -0,0 +1,7 @@ +fn test() { + fn nested() {} +} + +fn main() { + nested(); // { dg-error "Cannot find path .nested. in this scope" } +} diff --git a/gcc/testsuite/rust/compile/macro-issue1053-2.rs b/gcc/testsuite/rust/compile/macro-issue1053-2.rs new file mode 100644 index 00000000000..31459907c08 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro-issue1053-2.rs @@ -0,0 +1,5 @@ +macro_rules! m { + ($e:expr $(forbidden)*) => {{}}; // { dg-error "token .identifier. is not allowed after .expr. fragment" } + // { dg-error "required first macro rule in macro rules definition could not be parsed" "" { target *-*-* } .-1 } + // { dg-error "failed to parse item in crate" "" { target *-*-* } .-2 } +} diff --git a/gcc/testsuite/rust/compile/macro-issue1053.rs b/gcc/testsuite/rust/compile/macro-issue1053.rs new file mode 100644 index 00000000000..1e968496e0c --- /dev/null +++ b/gcc/testsuite/rust/compile/macro-issue1053.rs @@ -0,0 +1,3 @@ +macro_rules! m { + ($e:expr $(,)*) => {{}}; +} diff --git a/gcc/testsuite/rust/compile/macro-issue1224.rs b/gcc/testsuite/rust/compile/macro-issue1224.rs new file mode 100644 index 00000000000..003bbcd5067 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro-issue1224.rs @@ -0,0 +1,9 @@ +macro_rules! impl_uint { + ($($ty:ident),*) => { + impl $ty {} // { dg-error "metavariable is still repeating at this depth" } + // { dg-error "unrecognised token" "" { target *-*-* } .-1 } // Spurious + // { dg-error "could not parse type" "" { target *-*-* } .-2 } // Spurious + }; +} + +impl_uint!(u8, u16, u32, u64, u128); diff --git a/gcc/testsuite/rust/compile/macro-issue1233.rs b/gcc/testsuite/rust/compile/macro-issue1233.rs new file mode 100644 index 00000000000..7fab787b9e8 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro-issue1233.rs @@ -0,0 +1,22 @@ +// { dg-additional-options "-frust-cfg=A -w" } + +macro_rules! impl_uint { + ($($ty:ident = $lang:literal),*) => { + $( + impl $ty { + pub fn to_le(self) -> Self { + #[cfg(not(A))] + { + self + } + #[cfg(A)] + { + self + } + } + } + )* + } +} + +impl_uint!(u8 = "u8", u16 = "u16", u32 = "u32"); diff --git a/gcc/testsuite/rust/compile/macro-issue1395-2.rs b/gcc/testsuite/rust/compile/macro-issue1395-2.rs new file mode 100644 index 00000000000..1df6a3a0038 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro-issue1395-2.rs @@ -0,0 +1,7 @@ +// { dg-additional-options "-frust-edition=2018" } + +macro_rules! try { + // { dg-error "expecting .identifier. but .try. found" "" { target *-*-* } .-1 } + // { dg-error "failed to parse item in crate" "" { target *-*-* } .-2 } + () => {}; +} diff --git a/gcc/testsuite/rust/compile/macro-issue1395.rs b/gcc/testsuite/rust/compile/macro-issue1395.rs new file mode 100644 index 00000000000..b0368c1610f --- /dev/null +++ b/gcc/testsuite/rust/compile/macro-issue1395.rs @@ -0,0 +1,5 @@ +// Default edition is 2015 - this is valid + +macro_rules! try { + () => {}; +} diff --git a/gcc/testsuite/rust/compile/macro-issue1400-2.rs b/gcc/testsuite/rust/compile/macro-issue1400-2.rs new file mode 100644 index 00000000000..ba7b61b0b16 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro-issue1400-2.rs @@ -0,0 +1,32 @@ +macro_rules! foo { + ( ( $( $Trait: ident ),+ ) for $($Ty: ident)* ) => { + $( + impl $Trait for $Ty { + // { dg-error "different amount of matches used in merged repetitions: expected 4, got 1" "" { target *-*-* } .-1 } + 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} diff --git a/gcc/testsuite/rust/compile/macro-issue1400.rs b/gcc/testsuite/rust/compile/macro-issue1400.rs new file mode 100644 index 00000000000..971bd778054 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro-issue1400.rs @@ -0,0 +1,33 @@ +// { dg-additional-options "-w" } + +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} diff --git a/gcc/testsuite/rust/compile/macro1.rs b/gcc/testsuite/rust/compile/macro1.rs new file mode 100644 index 00000000000..8cd941891d0 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro1.rs @@ -0,0 +1,3 @@ +macro_rules! empty_parens { + () => (); +} diff --git a/gcc/testsuite/rust/compile/macro10.rs b/gcc/testsuite/rust/compile/macro10.rs new file mode 100644 index 00000000000..3f1453e2eda --- /dev/null +++ b/gcc/testsuite/rust/compile/macro10.rs @@ -0,0 +1,11 @@ +// { dg-additional-options "-w" } +macro_rules! foo { + {} => { + 15 + }; +} + +fn main() { + let a = foo!(); + let b = foo![]; +} diff --git a/gcc/testsuite/rust/compile/macro11.rs b/gcc/testsuite/rust/compile/macro11.rs new file mode 100644 index 00000000000..97b89a12d84 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro11.rs @@ -0,0 +1,11 @@ +macro_rules! call_f { + ($($f:ident)*) => { $($f();)* } +} + +fn f() {} + +// This is valid and should parse items +fn main() { + call_f!(f f f f); +} + diff --git a/gcc/testsuite/rust/compile/macro12.rs b/gcc/testsuite/rust/compile/macro12.rs new file mode 100644 index 00000000000..b75fbad2c2f --- /dev/null +++ b/gcc/testsuite/rust/compile/macro12.rs @@ -0,0 +1,8 @@ +// { dg-additional-options "-w" } +macro_rules! define_vars { + ($($v:ident)*) => { $(let $v = 15;)* } +} + +fn main() { + define_vars!(a0 b f __some_identifier); +} diff --git a/gcc/testsuite/rust/compile/macro13.rs b/gcc/testsuite/rust/compile/macro13.rs new file mode 100644 index 00000000000..eb8dfbbf393 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro13.rs @@ -0,0 +1,12 @@ +// { dg-additional-options "-w" } +macro_rules! create_type { + ($s:ident) => { + struct $s; + }; +} + +fn main() { + create_type!(A); + + let a = A; +} diff --git a/gcc/testsuite/rust/compile/macro14.rs b/gcc/testsuite/rust/compile/macro14.rs new file mode 100644 index 00000000000..b18c56eefc8 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro14.rs @@ -0,0 +1,10 @@ +// { dg-additional-options "-w" } +macro_rules! define_vars { + ($($v:ident)*) => { $(let $v = 15;)* } +} + +fn main() -> i32 { + define_vars!(a0 b f __some_identifier); + + b +} diff --git a/gcc/testsuite/rust/compile/macro15.rs b/gcc/testsuite/rust/compile/macro15.rs new file mode 100644 index 00000000000..02c739e415e --- /dev/null +++ b/gcc/testsuite/rust/compile/macro15.rs @@ -0,0 +1,12 @@ +// { dg-additional-options "-w" } +macro_rules! create_type { + ($s:ident) => { + struct $s; + }; +} + +create_type!(SomeOuterType); + +fn main() { + let a = SomeOuterType; +} diff --git a/gcc/testsuite/rust/compile/macro16.rs b/gcc/testsuite/rust/compile/macro16.rs new file mode 100644 index 00000000000..e5e56ed3f03 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro16.rs @@ -0,0 +1,11 @@ +fn main() { + macro_rules! create_type { + ($s:ident) => { + struct $s(i32); + }; + } + + create_type!(Wrapper); + + let _ = Wrapper(15); +} diff --git a/gcc/testsuite/rust/compile/macro17.rs b/gcc/testsuite/rust/compile/macro17.rs new file mode 100644 index 00000000000..743216529b7 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro17.rs @@ -0,0 +1,10 @@ +macro_rules! rep { + ($a:literal) => { $a }; // { dg-error "reached recursion limit" } + ($a:literal $(, $e:literal)*) => { // { dg-error "reached recursion limit" } + $a + rep!(0 $(, $e)*) // { dg-error "Failed to match" } + } +} + +fn main() -> i32 { + rep!(1, 2) +} diff --git a/gcc/testsuite/rust/compile/macro18.rs b/gcc/testsuite/rust/compile/macro18.rs new file mode 100644 index 00000000000..5418725b619 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro18.rs @@ -0,0 +1,14 @@ +// { dg-additional-options "-w" } + +macro_rules! take_stmt { + ($s:stmt) => { + $s; + }; +} + +fn main() -> i32 { + take_stmt!(let complete = 15;); // { dg-error "Failed to match any rule within macro" } + take_stmt!(let lacking = 14); + + 0 +} diff --git a/gcc/testsuite/rust/compile/macro19.rs b/gcc/testsuite/rust/compile/macro19.rs new file mode 100644 index 00000000000..1bf9a2bfa9d --- /dev/null +++ b/gcc/testsuite/rust/compile/macro19.rs @@ -0,0 +1,19 @@ +// { dg-additional-options "-w" } + +macro_rules! call_without_semi { + () => { + f() + }; + (block) => {{ + f() + }}; +} + +fn f() {} + +fn main() -> i32 { + call_without_semi!(); + call_without_semi!(block); + + 0 +} diff --git a/gcc/testsuite/rust/compile/macro2.rs b/gcc/testsuite/rust/compile/macro2.rs new file mode 100644 index 00000000000..a437655ef70 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro2.rs @@ -0,0 +1,3 @@ +macro_rules! empty_brackets { + [] => []; +} diff --git a/gcc/testsuite/rust/compile/macro20.rs b/gcc/testsuite/rust/compile/macro20.rs new file mode 100644 index 00000000000..9f3cbca012c --- /dev/null +++ b/gcc/testsuite/rust/compile/macro20.rs @@ -0,0 +1,16 @@ +macro_rules! define_trait { + ($assoc:ident, $i:item) => { + type $assoc; + + $i + }; +} + +trait DefinedThroughMacros { + define_trait!( + Inner, + fn takes_inner(i: Self::Inner) -> Self::Inner { + i + } + ); +} diff --git a/gcc/testsuite/rust/compile/macro21.rs b/gcc/testsuite/rust/compile/macro21.rs new file mode 100644 index 00000000000..9a1d773ec4b --- /dev/null +++ b/gcc/testsuite/rust/compile/macro21.rs @@ -0,0 +1,9 @@ +macro_rules! c_fn { + {$name:ident ($($arg_name:ident $arg_ty:ty),*) -> $ret_ty:ty} => { + fn $name($($arg_name: $arg_ty)*) -> $ret_ty; + }; +} + +extern "C" { + c_fn! {puts (s *const i8) -> i64} +} diff --git a/gcc/testsuite/rust/compile/macro22.rs b/gcc/testsuite/rust/compile/macro22.rs new file mode 100644 index 00000000000..bdc4bada270 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro22.rs @@ -0,0 +1,10 @@ +macro_rules! print { + () => { + fn puts(s: *const i8); + fn printf(fmt: *const i8, ...); + }; +} + +extern "C" { + print! {} +} diff --git a/gcc/testsuite/rust/compile/macro23.rs b/gcc/testsuite/rust/compile/macro23.rs new file mode 100644 index 00000000000..afaca9bc96b --- /dev/null +++ b/gcc/testsuite/rust/compile/macro23.rs @@ -0,0 +1,25 @@ +macro_rules! maybe_impl { + ($left:ident, $right:ident, $l_fn:ident, $r_fn:ident) => { + fn $l_fn(value: T) -> Maybe { + Maybe::$left(value) + } + + fn $r_fn() -> Maybe { + Maybe::$right + } + }; +} + +enum Maybe { + Just(T), + Nothing, +} + +impl Maybe { + maybe_impl!(Just, Nothing, just, nothing); +} + +fn main() { + let _ = Maybe::just(14); + let _: Maybe = Maybe::nothing(); +} diff --git a/gcc/testsuite/rust/compile/macro25.rs b/gcc/testsuite/rust/compile/macro25.rs new file mode 100644 index 00000000000..d92534c0747 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro25.rs @@ -0,0 +1,9 @@ +macro_rules! valid { + ($($a:literal)* $i:ident) => {{}}; +} + +fn main() { + valid!(1 one_lit); + valid!(identifier_only); + valid!(1 2 two_lits); +} diff --git a/gcc/testsuite/rust/compile/macro26.rs b/gcc/testsuite/rust/compile/macro26.rs new file mode 100644 index 00000000000..f6588e75eb0 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro26.rs @@ -0,0 +1,10 @@ +macro_rules! repeat { + ( $( $i:literal ),* ; $( $j:literal ),* ) => (( $( ($i,$j) ),* )) + // { dg-error "different amount of matches used in merged repetitions" "" { target *-*-* } .-1 } +} + +fn main() -> i32 { + let _ = repeat!(1, 2, 3; 2, 3); + + 0 +} diff --git a/gcc/testsuite/rust/compile/macro27.rs b/gcc/testsuite/rust/compile/macro27.rs new file mode 100644 index 00000000000..ee7833be0a6 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro27.rs @@ -0,0 +1,8 @@ +macro_rules! m { + ($a:expr tok) => { + // { dg-error "token .identifier. is not allowed after .expr. fragment" "" { target *-*-* } .-1 } + // { dg-error "required first macro rule in macro rules definition could not be parsed" "" { target *-*-* } .-2 } + // { dg-error "failed to parse item in crate" "" { target *-*-* } .-3 } + $a + }; +} diff --git a/gcc/testsuite/rust/compile/macro28.rs b/gcc/testsuite/rust/compile/macro28.rs new file mode 100644 index 00000000000..8002f284ecf --- /dev/null +++ b/gcc/testsuite/rust/compile/macro28.rs @@ -0,0 +1,8 @@ +macro_rules! m { + ($a:expr $(tok $es:expr)*) => { + // { dg-error "token .identifier. is not allowed after .expr. fragment" "" { target *-*-* } .-1 } + // { dg-error "required first macro rule in macro rules definition could not be parsed" "" { target *-*-* } .-2 } + // { dg-error "failed to parse item in crate" "" { target *-*-* } .-3 } + $a + }; +} diff --git a/gcc/testsuite/rust/compile/macro29.rs b/gcc/testsuite/rust/compile/macro29.rs new file mode 100644 index 00000000000..39f5021b74f --- /dev/null +++ b/gcc/testsuite/rust/compile/macro29.rs @@ -0,0 +1,8 @@ +macro_rules! m { + ($($es:expr)* tok) => { + // { dg-error "token .identifier. is not allowed after .expr. fragment" "" { target *-*-* } .-1 } + // { dg-error "required first macro rule in macro rules definition could not be parsed" "" { target *-*-* } .-2 } + // { dg-error "failed to parse item in crate" "" { target *-*-* } .-3 } + $a + }; +} diff --git a/gcc/testsuite/rust/compile/macro3.rs b/gcc/testsuite/rust/compile/macro3.rs new file mode 100644 index 00000000000..e5d3e93e07b --- /dev/null +++ b/gcc/testsuite/rust/compile/macro3.rs @@ -0,0 +1,3 @@ +macro_rules! empty_curlies { + {} => {}; +} diff --git a/gcc/testsuite/rust/compile/macro30.rs b/gcc/testsuite/rust/compile/macro30.rs new file mode 100644 index 00000000000..35064bc0ee5 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro30.rs @@ -0,0 +1,8 @@ +macro_rules! m { + ($e:expr $f:expr) => { + // { dg-error "fragment is not allowed after .expr. fragment" "" { target *-*-* } .-1 } + // { dg-error "required first macro rule in macro rules definition could not be parsed" "" { target *-*-* } .-2 } + // { dg-error "failed to parse item in crate" "" { target *-*-* } .-3 } + $e + }; +} diff --git a/gcc/testsuite/rust/compile/macro31.rs b/gcc/testsuite/rust/compile/macro31.rs new file mode 100644 index 00000000000..6674a5fe554 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro31.rs @@ -0,0 +1,8 @@ +macro_rules! m { + ($($e:expr)* $($f:expr)*) => { + // { dg-error "fragment is not allowed after .expr. fragment" "" { target *-*-* } .-1 } + // { dg-error "required first macro rule in macro rules definition could not be parsed" "" { target *-*-* } .-2 } + // { dg-error "failed to parse item in crate" "" { target *-*-* } .-3 } + $e + }; +} diff --git a/gcc/testsuite/rust/compile/macro32.rs b/gcc/testsuite/rust/compile/macro32.rs new file mode 100644 index 00000000000..d1d6305e6bd --- /dev/null +++ b/gcc/testsuite/rust/compile/macro32.rs @@ -0,0 +1,19 @@ +macro_rules! s { + ($s:stmt) => {{}}; +} + +macro_rules! multi_s { + ($($s:stmt)+) => {{}}; +} + +fn main() -> i32 { + s!(let a = 15); + s!(;); // Empty statement + s!(let a = 15;); // { dg-error "Failed to match any rule within macro" } + multi_s!(let a = 15;); + // ^ this actually gets parsed as two statements - one LetStmt and one + // empty statement. This is the same behavior as rustc, which you can + // see using a count!() macro + + 32 +} diff --git a/gcc/testsuite/rust/compile/macro33.rs b/gcc/testsuite/rust/compile/macro33.rs new file mode 100644 index 00000000000..2ccd33e50d3 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro33.rs @@ -0,0 +1,5 @@ +macro_rules! forbidden_frag { + ($t:ty $not_block:ident) => {{}}; // { dg-error "fragment specifier .ident. is not allowed after .ty. fragments" } + // { dg-error "required first macro rule in macro rules definition could not be parsed" "" { target *-*-* } .-1 } + // { dg-error "failed to parse item in crate" "" { target *-*-* } .-2 } +} diff --git a/gcc/testsuite/rust/compile/macro34.rs b/gcc/testsuite/rust/compile/macro34.rs new file mode 100644 index 00000000000..105d042fd50 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro34.rs @@ -0,0 +1,3 @@ +macro_rules! allowed_after_expr_matcher { + (($t:expr) bok) => {{}}; // follow-set restrictions do not apply after a matcher, but they do apply inside the matcher +} diff --git a/gcc/testsuite/rust/compile/macro35.rs b/gcc/testsuite/rust/compile/macro35.rs new file mode 100644 index 00000000000..07b157b53c2 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro35.rs @@ -0,0 +1,7 @@ +macro_rules! inside_matcher { + (($e:expr tok) tok) => {{}}; // { dg-error "token .identifier. is not allowed after .expr. fragment" } + // { dg-error "failed to parse macro matcher" "" { target *-*-* } .-1 } + // { dg-error "failed to parse macro match" "" { target *-*-* } .-2 } + // { dg-error "required first macro rule" "" { target *-*-* } .-3 } + // { dg-error "failed to parse item in crate" "" { target *-*-* } .-4 } +} diff --git a/gcc/testsuite/rust/compile/macro36.rs b/gcc/testsuite/rust/compile/macro36.rs new file mode 100644 index 00000000000..e5d66b22b7b --- /dev/null +++ b/gcc/testsuite/rust/compile/macro36.rs @@ -0,0 +1,3 @@ +macro_rules! ty_allowed { + ($t:ty $b:block) => {{}}; +} diff --git a/gcc/testsuite/rust/compile/macro37.rs b/gcc/testsuite/rust/compile/macro37.rs new file mode 100644 index 00000000000..5713d90130a --- /dev/null +++ b/gcc/testsuite/rust/compile/macro37.rs @@ -0,0 +1,5 @@ +macro_rules! invalid_after_zeroable { + ($e:expr $(,)* forbidden) => {{}}; // { dg-error "token .identifier. is not allowed after .expr. fragment" } + // { dg-error "required first macro rule" "" { target *-*-* } .-1 } + // { dg-error "failed to parse item in crate" "" { target *-*-* } .-2 } +} diff --git a/gcc/testsuite/rust/compile/macro38.rs b/gcc/testsuite/rust/compile/macro38.rs new file mode 100644 index 00000000000..eb294aec83b --- /dev/null +++ b/gcc/testsuite/rust/compile/macro38.rs @@ -0,0 +1,5 @@ +macro_rules! invalid_after_zeroable_multi { + ($e:expr $(,)? $(;)* $(=>)? forbidden) => {{}}; // { dg-error "token .identifier. is not allowed after .expr. fragment" } + // { dg-error "required first macro rule" "" { target *-*-* } .-1 } + // { dg-error "failed to parse item in crate" "" { target *-*-* } .-2 } +} diff --git a/gcc/testsuite/rust/compile/macro39.rs b/gcc/testsuite/rust/compile/macro39.rs new file mode 100644 index 00000000000..f5c498cc8ef --- /dev/null +++ b/gcc/testsuite/rust/compile/macro39.rs @@ -0,0 +1,5 @@ +macro_rules! m { + ($e:expr (, parenthesis_forbidden)) => {{}}; // { dg-error "token .\\(. at start of matcher is not allowed after .expr. fragment" } + // { dg-error "required first macro rule" "" { target *-*-* } .-1 } + // { dg-error "failed to parse item in crate" "" { target *-*-* } .-2 } +} diff --git a/gcc/testsuite/rust/compile/macro4.rs b/gcc/testsuite/rust/compile/macro4.rs new file mode 100644 index 00000000000..47ff6c93d87 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro4.rs @@ -0,0 +1,3 @@ +macro_rules! one_keyword { + (kw) => {}; +} diff --git a/gcc/testsuite/rust/compile/macro40.rs b/gcc/testsuite/rust/compile/macro40.rs new file mode 100644 index 00000000000..7151f3a83bc --- /dev/null +++ b/gcc/testsuite/rust/compile/macro40.rs @@ -0,0 +1,48 @@ +// { dg-additional-options "-w" } + +macro_rules! t { + () => { + i32 + }; +} + +macro_rules! s { + () => { + *const i8 + }; +} + +extern "C" { + fn printf(s: s!(), ...); +} + +fn square(arg: t!()) -> t!() { + let input: t!() = arg; + + input * input +} + +trait Trait { + fn f() -> t!(); + fn g(arg: t!()); +} + +struct Wrapper { + inner: t!(), +} + +impl Trait for Wrapper { + fn f() -> t!() { + 1 + } + + fn g(arg: t!()) {} +} + +fn id(arg: T) -> T { + arg +} + +fn main() { + id::(15); +} diff --git a/gcc/testsuite/rust/compile/macro41.rs b/gcc/testsuite/rust/compile/macro41.rs new file mode 100644 index 00000000000..38244222924 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro41.rs @@ -0,0 +1,13 @@ +macro_rules! empty { + ($($t:tt)*) => {}; +} + +empty! {nothing} +empty! {struct OuterItem;} +empty! {} + +fn main() { + empty! {as statement}; + empty! {any child item}; + empty! {}; +} diff --git a/gcc/testsuite/rust/compile/macro42.rs b/gcc/testsuite/rust/compile/macro42.rs new file mode 100644 index 00000000000..52d150b82ba --- /dev/null +++ b/gcc/testsuite/rust/compile/macro42.rs @@ -0,0 +1,32 @@ +// { dg-additional-options "-w -frust-cfg=A" } +#[rustc_builtin_macro] +macro_rules! cfg { + () => {{}}; +} + +fn main() -> i32 { + let mut res = 0; + if cfg!(A) { + res = 1; + } + + if cfg!(A) { + res = 2; + } else { + res = 3; + } + + if cfg!(A) { + res = 4; + } else if cfg!(A) { + res = 5; + } + + let res = if cfg!(A) { + 6 + } else { + 7 + }; + + return res; +} diff --git a/gcc/testsuite/rust/compile/macro5.rs b/gcc/testsuite/rust/compile/macro5.rs new file mode 100644 index 00000000000..a5d80952e28 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro5.rs @@ -0,0 +1,3 @@ +macro_rules! rust_keyword { + (fn) => {}; +} diff --git a/gcc/testsuite/rust/compile/macro6.rs b/gcc/testsuite/rust/compile/macro6.rs new file mode 100644 index 00000000000..0ca35ba6888 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro6.rs @@ -0,0 +1,11 @@ +macro_rules! zero_or_one { + ($($a:literal)?) => { // { dg-error "invalid amount of matches for macro invocation. Expected between 0 and 1, got 2" } + f(); + } +} + +fn main() { + zero_or_one!(); + zero_or_one!(14); + zero_or_one!(125 12 "gcc"); // { dg-error "Failed to match any rule within macro" } +} diff --git a/gcc/testsuite/rust/compile/macro7.rs b/gcc/testsuite/rust/compile/macro7.rs new file mode 100644 index 00000000000..abc48057c54 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro7.rs @@ -0,0 +1,13 @@ +fn f() {} + +macro_rules! one_or_more { + ($($a:literal)+) => { // { dg-error "invalid amount of matches for macro invocation" } + f(); + }; +} + +fn main() { + one_or_more!(1 1 1 1 1 1 1 1 1 1 1 "rust" 'c'); + one_or_more!(1); + one_or_more!(); // { dg-error "Failed to match any rule within macro" } +} diff --git a/gcc/testsuite/rust/compile/macro8.rs b/gcc/testsuite/rust/compile/macro8.rs new file mode 100644 index 00000000000..d3e8af93a6e --- /dev/null +++ b/gcc/testsuite/rust/compile/macro8.rs @@ -0,0 +1,12 @@ +fn f() {} + +macro_rules! expr { + ($($a:expr)?) => { + f(); + }; +} + +fn main() { + expr!(); + expr!(14); +} diff --git a/gcc/testsuite/rust/compile/macro9.rs b/gcc/testsuite/rust/compile/macro9.rs new file mode 100644 index 00000000000..9a59089b1e4 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro9.rs @@ -0,0 +1,17 @@ +macro_rules! add { + ($e:expr, $($es:expr),*) => { + $e + add!($($es),*) + }; + ($e:expr) => { + $e + }; +} + +fn main() -> i32 { + let a = add!(15 2 9); // { dg-error "Failed to match any rule within macro" } + let b = add!(15); + let b = add!(15 14); // { dg-error "Failed to match any rule within macro" } + let b = add!(15, 14,); // { dg-error "Failed to match any rule within macro" } + + 0 +} diff --git a/gcc/testsuite/rust/compile/macro_return.rs b/gcc/testsuite/rust/compile/macro_return.rs new file mode 100644 index 00000000000..8b06f875cc0 --- /dev/null +++ b/gcc/testsuite/rust/compile/macro_return.rs @@ -0,0 +1,10 @@ +// { dg-additional-options "-w" } + +macro_rules! add { + ($a:expr) => { $a }; + ($a:expr, $($b:expr),+) => { $a + add!($($b),*) } +} + +fn main() -> i32 { + add!(add!(1, 2)) +} diff --git a/gcc/testsuite/rust/compile/match1.rs b/gcc/testsuite/rust/compile/match1.rs new file mode 100644 index 00000000000..f649f3a1931 --- /dev/null +++ b/gcc/testsuite/rust/compile/match1.rs @@ -0,0 +1,16 @@ +enum Foo { + A, + B, + C(char), + D { x: i64, y: i64 }, +} + +fn inspect(f: Foo) { + match f { + Foo::A => {} + Foo::B => {} + Foo::C(a, b) => {} + // { dg-error "this pattern has 2 fields but the corresponding tuple variant has 1 field" "" { target *-*-* } .-1 } + Foo::D { x, y } => {} + } +} diff --git a/gcc/testsuite/rust/compile/match2.rs b/gcc/testsuite/rust/compile/match2.rs new file mode 100644 index 00000000000..359936a187c --- /dev/null +++ b/gcc/testsuite/rust/compile/match2.rs @@ -0,0 +1,15 @@ +enum Foo { + A, + B, + C(char), + D { x: i64, y: i64 }, +} + +fn inspect(f: Foo) { + match f { + Foo::A => {} + Foo::B => {} + Foo::C(x) => {} + Foo::D { y } => {} // { dg-error "pattern does not mention fields x" } + } +} diff --git a/gcc/testsuite/rust/compile/match3.rs b/gcc/testsuite/rust/compile/match3.rs new file mode 100644 index 00000000000..98181e85197 --- /dev/null +++ b/gcc/testsuite/rust/compile/match3.rs @@ -0,0 +1,16 @@ +enum Foo { + A, + B, + C(char), + D { x: i64, y: i64 }, +} + +fn inspect(f: Foo) { + match f { + Foo::A => {} + Foo::B => {} + Foo::C(x) => {} + Foo::D { z } => {} // { dg-error "variant D does not have a field named z" } + // { dg-error "pattern does not mention fields x, y" "" { target *-*-* } .-1 } + } +} diff --git a/gcc/testsuite/rust/compile/match4.rs b/gcc/testsuite/rust/compile/match4.rs new file mode 100644 index 00000000000..35b90a64fa5 --- /dev/null +++ b/gcc/testsuite/rust/compile/match4.rs @@ -0,0 +1,16 @@ +enum Foo { + A, + B, + C(char), + D { x: i64, y: i64 }, +} + +fn inspect(f: Foo) { + match f { + Foo::A => {} + Foo::B => {} + Foo::C { a } => {} + // { dg-error "expected struct variant, found tuple variant C" "" { target *-*-* } .-1 } + Foo::D { x, y } => {} + } +} diff --git a/gcc/testsuite/rust/compile/match5.rs b/gcc/testsuite/rust/compile/match5.rs new file mode 100644 index 00000000000..a5f934d6aeb --- /dev/null +++ b/gcc/testsuite/rust/compile/match5.rs @@ -0,0 +1,15 @@ +enum Foo { + A, + B, + C(char), + D { x: i64, y: i64 }, +} + +fn inspect(f: Foo) { + match f { + Foo::A => {} + Foo::B => {} + Foo::C(a) => {} + Foo::D(x, y) => {} // { dg-error "expected tuple struct or tuple variant, found struct variant 'Foo::D'" } + } +} diff --git a/gcc/testsuite/rust/compile/match6.rs b/gcc/testsuite/rust/compile/match6.rs new file mode 100644 index 00000000000..8fe06f7c116 --- /dev/null +++ b/gcc/testsuite/rust/compile/match6.rs @@ -0,0 +1,18 @@ +fn foo() -> bool { + true +} + +fn int32() -> i32 { + 1 +} + +fn bar() -> i32 { + match foo() { + true => int32(), + false => 0 + } +} + +fn main() -> () { + bar(); +} \ No newline at end of file diff --git a/gcc/testsuite/rust/compile/match7.rs b/gcc/testsuite/rust/compile/match7.rs new file mode 100644 index 00000000000..b16a1883522 --- /dev/null +++ b/gcc/testsuite/rust/compile/match7.rs @@ -0,0 +1,12 @@ +fn bar (x: u8, y: u8) -> i32 { + match (x, y) { + (1, 1) => { return 1; } + (1, _) => { return -1; } + } + + return 0; +} + +fn main () -> () { + bar (1, 2); +} diff --git a/gcc/testsuite/rust/compile/method1.rs b/gcc/testsuite/rust/compile/method1.rs new file mode 100644 index 00000000000..18652406085 --- /dev/null +++ b/gcc/testsuite/rust/compile/method1.rs @@ -0,0 +1,13 @@ +struct Foo(i32); +impl Foo { + fn test() {} +} + +pub fn main() { + let a; + a = Foo(123); + + a.test(); + // { dg-error "failed to resolve method for .test." "" { target *-*-* } .-1 } + // { dg-error {failed to type resolve expression} "" { target *-*-* } .-2 } +} diff --git a/gcc/testsuite/rust/compile/method2.rs b/gcc/testsuite/rust/compile/method2.rs new file mode 100644 index 00000000000..c8699f77c6a --- /dev/null +++ b/gcc/testsuite/rust/compile/method2.rs @@ -0,0 +1,16 @@ +struct Foo(A, B); + +impl Foo { + fn test(self, a: X) -> X { + a + } +} + +fn main() { + let a; + a = Foo(123, 456f32); + + let b; + b = a.test::(false); + // { dg-error "failed to resolve TypePath: asfasfr" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/mismatch-crate-name.rs b/gcc/testsuite/rust/compile/mismatch-crate-name.rs new file mode 100644 index 00000000000..e259b9e46cc --- /dev/null +++ b/gcc/testsuite/rust/compile/mismatch-crate-name.rs @@ -0,0 +1,4 @@ +// { dg-additional-options "-frust-crate=another_name" } +#![crate_name = "legit_name"] +// { dg-error ".-frust-crate-name. and .#.crate_name.. are required to match, but .another_name. does not match .legit_name." "" { target *-*-* } .-1 } +fn main() {} diff --git a/gcc/testsuite/rust/compile/missing_middle/both_path.rs b/gcc/testsuite/rust/compile/missing_middle/both_path.rs new file mode 100644 index 00000000000..5e5ad15457a --- /dev/null +++ b/gcc/testsuite/rust/compile/missing_middle/both_path.rs @@ -0,0 +1,3 @@ +pub fn f() -> u32 { + 5 +} diff --git a/gcc/testsuite/rust/compile/missing_middle/explicit.not.rs b/gcc/testsuite/rust/compile/missing_middle/explicit.not.rs new file mode 100644 index 00000000000..e28288b0f99 --- /dev/null +++ b/gcc/testsuite/rust/compile/missing_middle/explicit.not.rs @@ -0,0 +1 @@ +mod other; diff --git a/gcc/testsuite/rust/compile/missing_middle/inner_path.rs b/gcc/testsuite/rust/compile/missing_middle/inner_path.rs new file mode 100644 index 00000000000..daf4e3cc25a --- /dev/null +++ b/gcc/testsuite/rust/compile/missing_middle/inner_path.rs @@ -0,0 +1,3 @@ +pub fn f() -> u32 { + 4 +} diff --git a/gcc/testsuite/rust/compile/missing_middle/other.rs b/gcc/testsuite/rust/compile/missing_middle/other.rs new file mode 100644 index 00000000000..0c0884ec968 --- /dev/null +++ b/gcc/testsuite/rust/compile/missing_middle/other.rs @@ -0,0 +1,3 @@ +pub fn f() -> u32 { + 2 +} diff --git a/gcc/testsuite/rust/compile/missing_middle/outer_path.rs b/gcc/testsuite/rust/compile/missing_middle/outer_path.rs new file mode 100644 index 00000000000..fbe5074191b --- /dev/null +++ b/gcc/testsuite/rust/compile/missing_middle/outer_path.rs @@ -0,0 +1,3 @@ +pub fn f() -> u32 { + 3 +} 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/missing_return1.rs b/gcc/testsuite/rust/compile/missing_return1.rs new file mode 100644 index 00000000000..00bf393dbb9 --- /dev/null +++ b/gcc/testsuite/rust/compile/missing_return1.rs @@ -0,0 +1,6 @@ +// { dg-error "expected .* got .*" "" { target *-*-* } 0 } +fn test1() -> i32 {} + +fn main() { + let call1 = test1(); +} 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..79633407671 --- /dev/null +++ b/gcc/testsuite/rust/compile/mod_missing_middle.rs @@ -0,0 +1,29 @@ +// { dg-additional-options "-w" } + +mod missing_middle { + mod sub; + + #[path = "explicit.not.rs"] + mod explicit; +} + +#[path = "missing_middle"] +mod with_outer_path_attr { + #[path = "outer_path.rs"] + mod inner; +} + +mod with_inner_path_attr { + #![path = "missing_middle"] + + #[path = "inner_path.rs"] + mod inner; +} + +#[path = "missing_middle"] +mod with_both_path_attr { + #![path = "this_is_ignored"] + + #[path = "both_path.rs"] + mod inner; +} diff --git a/gcc/testsuite/rust/compile/never_type_err1.rs b/gcc/testsuite/rust/compile/never_type_err1.rs new file mode 100644 index 00000000000..52b1283fadf --- /dev/null +++ b/gcc/testsuite/rust/compile/never_type_err1.rs @@ -0,0 +1,14 @@ +fn test() { + let a; + + // FIXME: Unimplemented features + a = if true { // { dg-error "expected .T.. got .!." } + return; + } else { + return; + }; +} + +fn main() { + test(); +} diff --git a/gcc/testsuite/rust/compile/privacy1.rs b/gcc/testsuite/rust/compile/privacy1.rs new file mode 100644 index 00000000000..1cc83c04abe --- /dev/null +++ b/gcc/testsuite/rust/compile/privacy1.rs @@ -0,0 +1,11 @@ +mod orange { + mod green { + fn sain() {} + pub fn doux() {} + } + + fn brown() { + green::sain(); // { dg-error "definition is private in this context" } + green::doux(); + } +} diff --git a/gcc/testsuite/rust/compile/privacy2.rs b/gcc/testsuite/rust/compile/privacy2.rs new file mode 100644 index 00000000000..3c0744928b1 --- /dev/null +++ b/gcc/testsuite/rust/compile/privacy2.rs @@ -0,0 +1,13 @@ +// { dg-additional-options "-w" } + +mod orange { + fn tangerine() {} + + mod green { + mod blue { + fn berry() { + tangerine(); + } + } + } +} diff --git a/gcc/testsuite/rust/compile/privacy3.rs b/gcc/testsuite/rust/compile/privacy3.rs new file mode 100644 index 00000000000..d48acea4786 --- /dev/null +++ b/gcc/testsuite/rust/compile/privacy3.rs @@ -0,0 +1,28 @@ +mod orange { + mod green { + fn sain_void() {} + fn sain() -> bool { + false + } + pub fn doux() {} + } + + fn brown() { + if green::sain() { + // { dg-error "definition is private in this context" "" { target *-*-* } .-1 } + green::doux(); + } + + { + green::sain(); + // { dg-error "definition is private in this context" "" { target *-*-* } .-1 } + green::sain(); + // { dg-error "definition is private in this context" "" { target *-*-* } .-1 } + green::sain_void() + // { dg-error "definition is private in this context" "" { target *-*-* } .-1 } + } + + let a = green::sain(); + // { dg-error "definition is private in this context" "" { target *-*-* } .-1 } + } +} diff --git a/gcc/testsuite/rust/compile/privacy4.rs b/gcc/testsuite/rust/compile/privacy4.rs new file mode 100644 index 00000000000..d1ce0afd654 --- /dev/null +++ b/gcc/testsuite/rust/compile/privacy4.rs @@ -0,0 +1,19 @@ +mod orange { + mod green { + fn bean(value: T) -> T { + value + } + } + + fn brown() { + green::bean::(false); + // { dg-error "definition is private in this context" "" { target *-*-* } .-1 } + let a = green::bean::(15); + // { dg-error "definition is private in this context" "" { target *-*-* } .-1 } + + struct S; + + let s = green::bean(S); + // { dg-error "definition is private in this context" "" { target *-*-* } .-1 } + } +} diff --git a/gcc/testsuite/rust/compile/privacy5.rs b/gcc/testsuite/rust/compile/privacy5.rs new file mode 100644 index 00000000000..0e0e496dde2 --- /dev/null +++ b/gcc/testsuite/rust/compile/privacy5.rs @@ -0,0 +1,17 @@ +mod orange { + mod green { + struct Foo; + pub(in orange) struct Bar; + pub struct Baz; + } + + fn brown() { + let _ = green::Foo; // { dg-error "definition is private in this context" } + let _ = green::Bar; + let _ = green::Baz; + + let _: green::Foo; // { dg-error "definition is private in this context" } + + fn any(a0: green::Foo, a1: green::Bar) {} // { dg-error "20:definition is private in this context" } + } +} diff --git a/gcc/testsuite/rust/compile/privacy6.rs b/gcc/testsuite/rust/compile/privacy6.rs new file mode 100644 index 00000000000..487ed024209 --- /dev/null +++ b/gcc/testsuite/rust/compile/privacy6.rs @@ -0,0 +1,39 @@ +// { dg-additional-options "-w" } + +struct Adt; +enum EAdt { + V0, + V1, +} +struct Registers { + r0: i64, + r1: i64, + r2: i64, + r3: i64, +} +trait Foo {} + +fn foo1(value: bool) {} +fn foo2(value: char) {} +fn foo3(value: i32) {} +fn foo4(value: u16) {} +fn foo5(value: f64) {} +fn foo6(value: usize) {} +fn foo7(value: isize) {} +fn foo8(value: Adt) {} +fn foo9(value: EAdt) {} +fn foo10(value: &str) {} +fn foo11(value: *const i8) {} +fn foo12(value: T) {} +fn foo13(value: [i32; 5]) {} +fn foo14(value: [Adt]) {} +fn foo15(value: fn(i32) -> i32) {} +fn foo16(value: (i32, Adt)) {} +fn foo17(value: (i32, [f64; 5])) {} +fn foo18(value: Registers) {} +fn foo19(value: &dyn Foo) {} +fn foo20(value: &[Adt]) {} +// FIXME: Uncomment once #1257 is fixed +// fn foo21(value: fn(i32)) {} +// fn foo22(value: fn()) {} +fn foo23(value: fn() -> i32) {} diff --git a/gcc/testsuite/rust/compile/pub_restricted_1.rs b/gcc/testsuite/rust/compile/pub_restricted_1.rs new file mode 100644 index 00000000000..9bda9682403 --- /dev/null +++ b/gcc/testsuite/rust/compile/pub_restricted_1.rs @@ -0,0 +1,13 @@ +pub mod foo { + pub mod bar { + pub fn baz() {} + + pub(in foo::bar) struct A0; + } +} + +pub(in foo::fah::baz) struct A1; // { dg-error "cannot find simple path segment .fah." } +pub(in fro::bulator::saindoux) struct A2; // { dg-error "cannot find simple path segment .fro." } +pub(in foo::bar::saindoux) struct A3; // { dg-error "cannot find simple path segment .saindoux." } + +fn main() {} diff --git a/gcc/testsuite/rust/compile/pub_restricted_2.rs b/gcc/testsuite/rust/compile/pub_restricted_2.rs new file mode 100644 index 00000000000..8588f2775ca --- /dev/null +++ b/gcc/testsuite/rust/compile/pub_restricted_2.rs @@ -0,0 +1,18 @@ +// { dg-additional-options "-w" } + +mod foo { + mod bar { + mod baz { + pub(in baz) struct A0; + pub(in bar::baz) struct A1; + pub(in foo::bar::baz) struct A2; + + mod sain { + mod doux {} + } + + pub(in sain) struct A3; // { dg-error "restricted path is not an ancestor of the current module" } + pub(in sain::doux) struct A4; // { dg-error "restricted path is not an ancestor of the current module" } + } + } +} diff --git a/gcc/testsuite/rust/compile/pub_restricted_3.rs b/gcc/testsuite/rust/compile/pub_restricted_3.rs new file mode 100644 index 00000000000..d477385d761 --- /dev/null +++ b/gcc/testsuite/rust/compile/pub_restricted_3.rs @@ -0,0 +1,11 @@ +// { dg-additional-options "-w" } + +mod foo { + mod bar { + pub(in foo) fn baz() {} + } + + fn baz() { + bar::baz(); // no error, foo::bar::baz is public in foo + } +} diff --git a/gcc/testsuite/rust/compile/raw_identifiers_bad_keywords.rs b/gcc/testsuite/rust/compile/raw_identifiers_bad_keywords.rs new file mode 100644 index 00000000000..854d7e6edee --- /dev/null +++ b/gcc/testsuite/rust/compile/raw_identifiers_bad_keywords.rs @@ -0,0 +1,3 @@ +pub fn plus(n: i32, m: i32) -> i32 { + r#crate /* { dg-error "forbidden raw identifier" } */ +} diff --git a/gcc/testsuite/rust/compile/raw_identifiers_underscore.rs b/gcc/testsuite/rust/compile/raw_identifiers_underscore.rs new file mode 100644 index 00000000000..86e9013a50b --- /dev/null +++ b/gcc/testsuite/rust/compile/raw_identifiers_underscore.rs @@ -0,0 +1,3 @@ +pub fn s(num: i32) -> i32 { + r#_ * num /* { dg-error "not a valid raw identifier" } */ +} diff --git a/gcc/testsuite/rust/compile/rawbytestring.rs b/gcc/testsuite/rust/compile/rawbytestring.rs new file mode 100644 index 0000000000000000000000000000000000000000..9c6b762a7fd378206a3bfe21db5b708890f5466f GIT binary patch literal 3234 zcmbVOO>fgc5amjL#mG4T6)1rVl`5`1a^M^Zc^f;m2zI;c($Wfvf5=~A-pqd4PU65Z z<9Tmp-n`vS-O~56Y3cQwv*$CS<&wUX59E5=v|Go4UDeZ9>ni$0wkR&M$OnWLi=tR8 zvhYe0>#n0kp8Z~u3yqU0ZIOclm4066_dMaIdKBLE90VG(Y=lGOCeT&0tuLp+z$p*Er0}$>V{I!^8|YFtTxx z@X*l4>D0{rUt=35bE5|t9J_s{&GuboZD*@|GH+hjmxkvqUg|FRiNY&& zP6(%e4anlh3W@7JWKOd9E)p`E*!Jfr70=|kILq??taYC%vd4tW9O052FwtHy(W1l^5)-!Q6rkeY2pcOb5 zC5~Q^#`Cf!S&N9GM~?nelacMDHe;2ejYcV-D%(M~7r|5FJ&7hOIQ$Oo!_o8>9i>^x zV>X-Uc!7Jfq5+jI?0J=nn!sj`v1wMcU}PH?O>D8bJ*^GcSU|ak{Lxs!g8aAiFN}Pz A0RR91 literal 0 HcmV?d00001 diff --git a/gcc/testsuite/rust/compile/redef_error1.rs b/gcc/testsuite/rust/compile/redef_error1.rs new file mode 100644 index 00000000000..ae51e36c87f --- /dev/null +++ b/gcc/testsuite/rust/compile/redef_error1.rs @@ -0,0 +1,8 @@ +struct S1 { + x: f64, + y: f64, +} + +struct S1(i32, bool); // { dg-error "redefined multiple times" } + +fn main() {} diff --git a/gcc/testsuite/rust/compile/redef_error2.rs b/gcc/testsuite/rust/compile/redef_error2.rs new file mode 100644 index 00000000000..65793bcda8a --- /dev/null +++ b/gcc/testsuite/rust/compile/redef_error2.rs @@ -0,0 +1,4 @@ +const TEST: i32 = 2; +const TEST: f32 = 3.0; // { dg-error "redefined multiple times" } + +fn main() {} diff --git a/gcc/testsuite/rust/compile/redef_error3.rs b/gcc/testsuite/rust/compile/redef_error3.rs new file mode 100644 index 00000000000..a4bf1ed3d8c --- /dev/null +++ b/gcc/testsuite/rust/compile/redef_error3.rs @@ -0,0 +1,9 @@ +fn test() -> bool { + true +} + +fn test() -> i32 { // { dg-error "redefined multiple times" } + 123 +} + +fn main() {} diff --git a/gcc/testsuite/rust/compile/redef_error4.rs b/gcc/testsuite/rust/compile/redef_error4.rs new file mode 100644 index 00000000000..a250c0ac00e --- /dev/null +++ b/gcc/testsuite/rust/compile/redef_error4.rs @@ -0,0 +1,27 @@ +struct Foo(i32, bool); + +impl Foo { + fn new(a: i32, b: bool) -> Foo { + Foo(a, b) + } + + fn test() -> i32 { + test() + } + + fn test() -> bool { // { dg-error "redefined multiple times" } + true + } +} + +fn test() -> i32 { + 123 +} + +fn main() { + let a; + a = Foo::new(1, true); + + let b; + b = Foo::test(); +} diff --git a/gcc/testsuite/rust/compile/redef_error5.rs b/gcc/testsuite/rust/compile/redef_error5.rs new file mode 100644 index 00000000000..dc6ad50e104 --- /dev/null +++ b/gcc/testsuite/rust/compile/redef_error5.rs @@ -0,0 +1,8 @@ +struct Foo(i32, bool); + +impl Foo { + const TEST: i32 = 123; + const TEST: bool = false; // { dg-error "redefined multiple times" } +} + +fn main() {} diff --git a/gcc/testsuite/rust/compile/redef_error6.rs b/gcc/testsuite/rust/compile/redef_error6.rs new file mode 100644 index 00000000000..664c6ae9894 --- /dev/null +++ b/gcc/testsuite/rust/compile/redef_error6.rs @@ -0,0 +1,13 @@ +struct Foo(T, usize); + +impl Foo { + fn test() -> i32 { + 123 + } + + fn test(self) -> i32 { // { dg-error "redefined multiple times" } + self.0 + } +} + +fn main() {} diff --git a/gcc/testsuite/rust/compile/reference1.rs b/gcc/testsuite/rust/compile/reference1.rs new file mode 100644 index 00000000000..ff791533754 --- /dev/null +++ b/gcc/testsuite/rust/compile/reference1.rs @@ -0,0 +1,6 @@ +fn main() { + let a = &123; + let b: &mut i32 = a; + // { dg-error "mismatched mutability" "" { target *-*-* } .-1 } + // { dg-error "expected .&mut i32. got .& i32." "" { target *-*-* } .-2 } +} diff --git a/gcc/testsuite/rust/compile/self-path1.rs b/gcc/testsuite/rust/compile/self-path1.rs new file mode 100644 index 00000000000..425ba848fc0 --- /dev/null +++ b/gcc/testsuite/rust/compile/self-path1.rs @@ -0,0 +1,12 @@ +// { dg-additional-options "-w" } +struct foo; + +fn bar() -> self::foo { + crate::foo +} + +fn baz() { + let a: foo = self::bar(); + + crate::bar(); +} diff --git a/gcc/testsuite/rust/compile/self-path2.rs b/gcc/testsuite/rust/compile/self-path2.rs new file mode 100644 index 00000000000..b9b82cae5a6 --- /dev/null +++ b/gcc/testsuite/rust/compile/self-path2.rs @@ -0,0 +1,21 @@ +// { dg-additional-options "-w" } +struct foo; + +fn bar() -> self::foo { + crate::foo +} + +fn baz() { + let a: foo = self::bar(); + + crate::bar(); + + crate::self::foo(); + // { dg-error "failed to resolve: .self. in paths can only be used in start position" "" { target *-*-* } .-1 } +} + +type a = foo; +type b = crate::foo; +type c = self::foo; +type d = crate::self::foo; +// { dg-error "failed to resolve: .self. in paths can only be used in start position" "" { target *-*-* } .-1 } diff --git a/gcc/testsuite/rust/compile/shadow1.rs b/gcc/testsuite/rust/compile/shadow1.rs new file mode 100644 index 00000000000..77410e932da --- /dev/null +++ b/gcc/testsuite/rust/compile/shadow1.rs @@ -0,0 +1,7 @@ +fn main() { + let mut x = 5; + let mut x; + x = true; + x = x + 2; // { dg-error "cannot apply this operator to types bool and " } + // { dg-error {failed to type resolve expression} "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/specify-crate-name.rs b/gcc/testsuite/rust/compile/specify-crate-name.rs new file mode 100644 index 00000000000..a8679157024 --- /dev/null +++ b/gcc/testsuite/rust/compile/specify-crate-name.rs @@ -0,0 +1,7 @@ +// { dg-additional-options "-frust-crate=fancy_crate_name -fdump-tree-gimple" } +pub fn does_nothing() {} +fn main() { + does_nothing() +} +// { dg-final { scan-tree-dump-times {fancy_crate_name::does_nothing} 2 gimple } } +// { dg-final { scan-tree-dump-times {fancy_crate_name::main} 1 gimple } } diff --git a/gcc/testsuite/rust/compile/static_var1.rs b/gcc/testsuite/rust/compile/static_var1.rs new file mode 100644 index 00000000000..b3b5751c932 --- /dev/null +++ b/gcc/testsuite/rust/compile/static_var1.rs @@ -0,0 +1,5 @@ +static x = 3; // { dg-error "expecting ':' but '=' found" } + +fn main() {// { dg-error "failed to parse item in crate" } + let y = x +1; +} diff --git a/gcc/testsuite/rust/compile/stmt_with_block_err1.rs b/gcc/testsuite/rust/compile/stmt_with_block_err1.rs new file mode 100644 index 00000000000..8780d0feeac --- /dev/null +++ b/gcc/testsuite/rust/compile/stmt_with_block_err1.rs @@ -0,0 +1,17 @@ +fn test(x: i32) -> i32 { + if x > 1 { // { dg-error "expected .... got .." } + 1 + } else { + 2 + } + + { // { dg-error "expected .... got .." } + 3 + } + + 3 +} + +fn main() { + let a = test(0); +} diff --git a/gcc/testsuite/rust/compile/struct_align1.rs b/gcc/testsuite/rust/compile/struct_align1.rs new file mode 100644 index 00000000000..22eb6bc80fb --- /dev/null +++ b/gcc/testsuite/rust/compile/struct_align1.rs @@ -0,0 +1,19 @@ +#[repr(align(8))] +struct Foo { + x: i16, + // { dg-warning "field is never read" "" { target *-*-* } .-1 } + y: i8, + // { dg-warning "field is never read" "" { target *-*-* } .-1 } + z: i32, + // { dg-warning "field is never read" "" { target *-*-* } .-1 } +} + +#[repr(align(8))] +struct Bar(i8, i32); + +fn main () { + let f = Foo { x: 5, y: 2, z: 13 }; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let b = Bar (7, 262); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/struct_align2.rs b/gcc/testsuite/rust/compile/struct_align2.rs new file mode 100644 index 00000000000..ac490643a36 --- /dev/null +++ b/gcc/testsuite/rust/compile/struct_align2.rs @@ -0,0 +1,18 @@ + +fn main () { + + #[repr(align(8))] + struct Baz { + x: u16, + y: u32, + }; + + #[repr(align(4))] + struct Qux (u8, i16); + + let b = Baz { x: 5, y: 1984 }; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let c = Qux (1, 2); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/struct_init1.rs b/gcc/testsuite/rust/compile/struct_init1.rs new file mode 100644 index 00000000000..1875fb4f33e --- /dev/null +++ b/gcc/testsuite/rust/compile/struct_init1.rs @@ -0,0 +1,10 @@ +struct Foo { + a: f32, + b: f32, +} + +fn main() { + let a = Foo { 0: 10.0, 1: 20.0 }; // { dg-error "failed to resolve type for field" } + // { dg-error "unknown field" "" { target *-*-* } .-1 } + // { dg-prune-output "compilation terminated" } +} diff --git a/gcc/testsuite/rust/compile/struct_pack1.rs b/gcc/testsuite/rust/compile/struct_pack1.rs new file mode 100644 index 00000000000..eb9d879c1dc --- /dev/null +++ b/gcc/testsuite/rust/compile/struct_pack1.rs @@ -0,0 +1,19 @@ +#[repr(packed(2))] +struct Foo { + x: i16, + // { dg-warning "field is never read" "" { target *-*-* } .-1 } + y: i8, + // { dg-warning "field is never read" "" { target *-*-* } .-1 } + z: i32, + // { dg-warning "field is never read" "" { target *-*-* } .-1 } +} + +#[repr(packed)] +struct Bar(i8, i32); + +fn main () { + let f = Foo { x: 5, y: 2, z: 13 }; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let b = Bar (7, 262); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/struct_pack2.rs b/gcc/testsuite/rust/compile/struct_pack2.rs new file mode 100644 index 00000000000..e5f74c20bb0 --- /dev/null +++ b/gcc/testsuite/rust/compile/struct_pack2.rs @@ -0,0 +1,18 @@ + +fn main () { + + #[repr(packed(2))] + struct Baz { + x: u16, + y: u32, + }; + + #[repr(packed)] + struct Qux (u8, i16); + + let b = Baz { x: 5, y: 1984 }; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let c = Qux (1, 2); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/syntax-only.rs b/gcc/testsuite/rust/compile/syntax-only.rs new file mode 100644 index 00000000000..cd84907bf84 --- /dev/null +++ b/gcc/testsuite/rust/compile/syntax-only.rs @@ -0,0 +1,6 @@ +// { dg-additional-options "-fsyntax-only" } + +fn main() { + let mut a = 15; + a = true; +} diff --git a/gcc/testsuite/rust/compile/test_mod.rs b/gcc/testsuite/rust/compile/test_mod.rs new file mode 100644 index 00000000000..4b3c000236b --- /dev/null +++ b/gcc/testsuite/rust/compile/test_mod.rs @@ -0,0 +1,6 @@ +//! test_mod inner doc comment +//! +//! foo bar baz cake pizza carbs + +pub struct Test(pub i32); +// { dg-warning "struct is never constructed" "" { target *-*-* } .-1 } diff --git a/gcc/testsuite/rust/compile/torture/all_doc_comment_line_blocks.rs b/gcc/testsuite/rust/compile/torture/all_doc_comment_line_blocks.rs new file mode 100644 index 00000000000..b7368ba29ee --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/all_doc_comment_line_blocks.rs @@ -0,0 +1,45 @@ +// comment line not a doc +/* comment block not a doc */ + +//! inner line comment for most outer crate +/*! inner block comment for most outer crate */ + +// comment line not a doc +/* comment block not a doc */ + +/// outer doc line for module +/** outer doc block for module */ +pub mod module { + //! inner line doc + //!! inner line doc! + /*! inner block doc */ + /*!! inner block doc! */ + + // line comment + /// outer line doc + //// line comment + + /* block comment */ + /** outer block doc */ + /*** block comment */ + + mod block_doc_comments { + /* /* */ /** */ /*! */ */ + /*! /* */ /** */ /*! */ */ + /** /* */ /** */ /*! */ */ + mod item {} + } + + pub mod empty { + //! + /*!*/ + // + + /// + // the following warning is issued one line earlier + mod doc {} + /**/ + /***/ + } +} +pub fn main() {} diff --git a/gcc/testsuite/rust/compile/torture/all_doc_comment_line_blocks_crlf.rs b/gcc/testsuite/rust/compile/torture/all_doc_comment_line_blocks_crlf.rs new file mode 100644 index 00000000000..9f2f2207397 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/all_doc_comment_line_blocks_crlf.rs @@ -0,0 +1,48 @@ +// comment line not a doc +/* comment block not a doc */ + +//! inner line comment for most outer crate +/*! inner block comment for most outer crate */ + +// comment line not a doc +/* comment block not a doc */ + +/// outer doc line for module +/** outer doc block for module */ +pub mod module +{ + //! inner line doc + //!! inner line doc! + /*! inner block doc */ + /*!! inner block doc! */ + + // line comment + /// outer line doc + //// line comment + + /* block comment */ + /** outer block doc */ + /*** block comment */ + + mod block_doc_comments + { + /* /* */ /** */ /*! */ */ + /*! /* */ /** */ /*! */ */ + /** /* */ /** */ /*! */ */ + mod item { } + } + + pub mod empty + { + //! + /*!*/ + // + + /// + mod doc { } + + /**/ + /***/ + } +} +pub fn main () { } diff --git a/gcc/testsuite/rust/compile/torture/arithmetic_expressions1.rs b/gcc/testsuite/rust/compile/torture/arithmetic_expressions1.rs new file mode 100644 index 00000000000..4c3ee77c835 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/arithmetic_expressions1.rs @@ -0,0 +1,30 @@ +// { dg-prune-output "warning: unused name" } as there are many of these expected. + +fn main() { + let a: i32 = 1; + let b: f32 = 5f32; + let c: bool = true; + + let a1: i32 = a + 1; + let a2: i32 = a - 2; + let a3: i32 = a * 3; + let a4: i32 = a / 4; + let a5: i32 = a % 5; + + let b1: f32 = b + 1f32; + let b2: f32 = b - 2f32; + let b3: f32 = b * 3f32; + let b4: f32 = b / 4f32; + // let b5: f32 = b % 5f32; + + let aa1: i32 = a & 1; + let aa2: i32 = a | 2; + let aa2: i32 = a ^ 3; + + let c1: bool = c & true; + let c2: bool = c | false; + let c3: bool = c ^ true; + + let aaa1: i32 = a << 1; + let aaa2: i32 = a >> 2; +} diff --git a/gcc/testsuite/rust/compile/torture/array_const_fold_1.rs b/gcc/testsuite/rust/compile/torture/array_const_fold_1.rs new file mode 100644 index 00000000000..e45c9389c93 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/array_const_fold_1.rs @@ -0,0 +1,2 @@ +const TEST: [i32; 16] = [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8]; +// { dg-warning "unused name" "" { target *-*-* } .-1 } \ No newline at end of file diff --git a/gcc/testsuite/rust/compile/torture/array_const_fold_2.rs b/gcc/testsuite/rust/compile/torture/array_const_fold_2.rs new file mode 100644 index 00000000000..b42a68e5ddb --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/array_const_fold_2.rs @@ -0,0 +1,3 @@ +const SIZE: usize = 14 + 2; +const TEST: [i32; SIZE] = [2; SIZE]; +// { dg-warning "unused name" "" { target *-*-* } .-1 } diff --git a/gcc/testsuite/rust/compile/torture/array_function.rs b/gcc/testsuite/rust/compile/torture/array_function.rs new file mode 100644 index 00000000000..4e2b2e03f31 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/array_function.rs @@ -0,0 +1,8 @@ +fn foo() -> i32 { + 1 +} + + +fn main() { + let _a: [i32; 1] = [foo()]; +} \ No newline at end of file diff --git a/gcc/testsuite/rust/compile/torture/array_type_infer.rs b/gcc/testsuite/rust/compile/torture/array_type_infer.rs new file mode 100644 index 00000000000..6f21bf2420c --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/array_type_infer.rs @@ -0,0 +1,4 @@ +fn main() { + let arr: [_; 5] = [1, 2, 3, 4, 5]; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/array_zero_length.rs b/gcc/testsuite/rust/compile/torture/array_zero_length.rs new file mode 100644 index 00000000000..3155b1c48c0 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/array_zero_length.rs @@ -0,0 +1,4 @@ +fn main() { + let arr = ["Hello"; 0]; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/arrays1.rs b/gcc/testsuite/rust/compile/torture/arrays1.rs new file mode 100644 index 00000000000..7250e0fa2af --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/arrays1.rs @@ -0,0 +1,9 @@ +fn main() { + let xs: [i32; 5] = [1, 2, 3, 4, 5]; + let xy = [6, 7, 8]; + + let a = xs[0]; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let b = xy[2]; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/arrays2.rs b/gcc/testsuite/rust/compile/torture/arrays2.rs new file mode 100644 index 00000000000..55491f34524 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/arrays2.rs @@ -0,0 +1,8 @@ +fn main() { + let mut array: [i32; 3] = [0; 3]; + + let a = array[0]; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let mut c; + c = array[2]; +} diff --git a/gcc/testsuite/rust/compile/torture/arrays3.rs b/gcc/testsuite/rust/compile/torture/arrays3.rs new file mode 100644 index 00000000000..372d969aa07 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/arrays3.rs @@ -0,0 +1,6 @@ +const TEST: usize = 6; + +fn main() { + let a: [_; 12] = [123; TEST * 2]; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/arrays4.rs b/gcc/testsuite/rust/compile/torture/arrays4.rs new file mode 100644 index 00000000000..ac317fedf44 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/arrays4.rs @@ -0,0 +1,6 @@ +const TEST: usize = 4; + +fn main() { + let a: [_; TEST + 1 + 2] = [123; 7]; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/arrays5.rs b/gcc/testsuite/rust/compile/torture/arrays5.rs new file mode 100644 index 00000000000..58950a17a15 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/arrays5.rs @@ -0,0 +1,6 @@ + +// Checks that we don't try to allocate a 4TB array during compilation +fn main () { + let x = [0; 4 * 1024 * 1024 * 1024 * 1024]; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/arrays6.rs b/gcc/testsuite/rust/compile/torture/arrays6.rs new file mode 100644 index 00000000000..c7212d3f183 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/arrays6.rs @@ -0,0 +1,10 @@ + +// Checks that we don't try to allocate a 4TB array during compilation +fn foo() -> [u8; 4 * 1024 * 1024 * 1024 * 1024] { + [0; 4 * 1024 * 1024 * 1024 * 1024] +} + +fn main () { + let x = foo (); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/arrays_index1.rs b/gcc/testsuite/rust/compile/torture/arrays_index1.rs new file mode 100644 index 00000000000..1fe5de91bcf --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/arrays_index1.rs @@ -0,0 +1,9 @@ +fn main() { + let mut array: [i32; 3] = [0; 3]; + + let a = array[0]; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let x = 0; + let mut c; + c = array[x+1]; +} diff --git a/gcc/testsuite/rust/compile/torture/arrays_index2.rs b/gcc/testsuite/rust/compile/torture/arrays_index2.rs new file mode 100644 index 00000000000..f9bee7748ee --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/arrays_index2.rs @@ -0,0 +1,4 @@ +fn main() { + let mut array: [i32; 3] = [0; 3]; + array[0] = 1; +} diff --git a/gcc/testsuite/rust/compile/torture/arrays_index3.rs b/gcc/testsuite/rust/compile/torture/arrays_index3.rs new file mode 100644 index 00000000000..8fa0a226d02 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/arrays_index3.rs @@ -0,0 +1,15 @@ +fn foo() -> usize { + 1 +} + +fn bar() -> [i32; 1] { + [0] +} + + + +fn main() -> () { + let a = [10]; + let _b = a[foo()]; + let _c = bar()[foo()]; +} diff --git a/gcc/testsuite/rust/compile/torture/as_bool_char.rs b/gcc/testsuite/rust/compile/torture/as_bool_char.rs new file mode 100644 index 00000000000..d687499384a --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/as_bool_char.rs @@ -0,0 +1,36 @@ +extern "C" { fn abort (); } + +pub fn main () +{ + let t = true; + let f = false; + let one = t as u8; + let zero = f as u8; + + if one != 1 || zero != 0 { unsafe { abort (); } } + + let isizeone = true as isize; + let usizezero = false as usize; + + if isizeone != 1 || usizezero != 0 { unsafe { abort (); } } + + let i32zero = f as i32; + let u128one = t as u128; + + if u128one != 1 || i32zero != 0 { unsafe { abort (); } } + + let a = 'a'; + let b = 'b'; + let ua = a as u8; + let ib = b as i32; + + if (ua + 1) as i32 != ib { unsafe { abort (); } } + + let tt = ua; + let aa = tt as char; + + let ttt = tt + 1; + let ab = ttt as char; + + if aa != 'a' || ab != 'b' { unsafe { abort (); } } +} diff --git a/gcc/testsuite/rust/compile/torture/associated_types1.rs b/gcc/testsuite/rust/compile/torture/associated_types1.rs new file mode 100644 index 00000000000..bf181df7045 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/associated_types1.rs @@ -0,0 +1,12 @@ +pub trait Foo { + type A; + + fn boo(&self) -> ::A; +} + +fn foo2(x: I) { + // { dg-warning "function is never used: .foo2." "" { target *-*-* } .-1 } + x.boo(); +} + +pub fn main() {} diff --git a/gcc/testsuite/rust/compile/torture/autoderef1.rs b/gcc/testsuite/rust/compile/torture/autoderef1.rs new file mode 100644 index 00000000000..0cf070f1f37 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/autoderef1.rs @@ -0,0 +1,15 @@ +struct Foo(i32, bool); +struct Bar { + a: i32, + b: bool, +} + +fn main() { + let a = &Foo(123, false); + let _b: i32 = a.0; + let _c: bool = a.1; + + let a = &Bar { a: 456, b: false }; + let _b: i32 = a.a; + let _c: bool = a.b; +} diff --git a/gcc/testsuite/rust/compile/torture/block_expr1.rs b/gcc/testsuite/rust/compile/torture/block_expr1.rs new file mode 100644 index 00000000000..011cc1fc89d --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/block_expr1.rs @@ -0,0 +1,29 @@ +fn test3(x: i32) -> i32 { + if x > 1 { + 5 + } else { + 0 + } +} + +fn test5(x: i32) -> i32 { + if x > 1 { + if x == 5 { + 7 + } else { + 9 + } + } else { + 0 + } +} + +fn main() { + let call3: i32 = { test3(3) + 2 }; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let call5 = { + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let a = test5(5); + a + 1 + }; +} diff --git a/gcc/testsuite/rust/compile/torture/block_expr2.rs b/gcc/testsuite/rust/compile/torture/block_expr2.rs new file mode 100644 index 00000000000..7c3ff698097 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/block_expr2.rs @@ -0,0 +1,15 @@ +fn test() -> i32 { + 123 +} + +fn main() { + let a = { test() }; + let b = { + // { dg-warning "unused name" "" { target *-*-* } .-1 } + if a > 10 { + a - 1 + } else { + a + 1 + } + }; +} diff --git a/gcc/testsuite/rust/compile/torture/block_expr3.rs b/gcc/testsuite/rust/compile/torture/block_expr3.rs new file mode 100644 index 00000000000..6914b6379d7 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/block_expr3.rs @@ -0,0 +1,14 @@ +fn main() { + let x = 111; + + let a = { + // { dg-warning "unused name" "" { target *-*-* } .-1 } + if x == 10 { + 123 + } else if x < 10 { + 456 + } else { + 789 + } + }; +} diff --git a/gcc/testsuite/rust/compile/torture/block_expr4.rs b/gcc/testsuite/rust/compile/torture/block_expr4.rs new file mode 100644 index 00000000000..da033ef9ef4 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/block_expr4.rs @@ -0,0 +1,8 @@ +fn foo() -> isize { + 0 +} + +fn main() { + let a = foo(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/block_expr5.rs b/gcc/testsuite/rust/compile/torture/block_expr5.rs new file mode 100644 index 00000000000..7e164a949bb --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/block_expr5.rs @@ -0,0 +1,40 @@ +fn foo() -> i32 { + 0 +} + +fn bar() -> i32 { + foo(); + foo() +} + +fn baz() -> i32 { + { + bar(); + bar(); + } + { + bar(); + bar() + }; + { + bar(); + bar() + } +} + +fn test(ok: i32) -> i32 { + if ok >= 1 { + foo() + } else if ok <= -1 { + bar() + } else { + baz() + } +} + +fn main() { + let a = foo(); + let b = bar(); + let c = baz(); + test(a + b + c); +} diff --git a/gcc/testsuite/rust/compile/torture/block_expr_parser_bug.rs b/gcc/testsuite/rust/compile/torture/block_expr_parser_bug.rs new file mode 100644 index 00000000000..468aace9881 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/block_expr_parser_bug.rs @@ -0,0 +1,5 @@ +fn main() { + let a = 123; + let b = if a > 10 { a - 1 } else { a + 1 }; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/bom.rs b/gcc/testsuite/rust/compile/torture/bom.rs new file mode 100644 index 00000000000..5edcab227ee --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/bom.rs @@ -0,0 +1 @@ +pub fn main () { } diff --git a/gcc/testsuite/rust/compile/torture/bom_comment.rs b/gcc/testsuite/rust/compile/torture/bom_comment.rs new file mode 100644 index 00000000000..020e1707b55 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/bom_comment.rs @@ -0,0 +1,2 @@ +// UTF8 BOM +pub fn main () { } diff --git a/gcc/testsuite/rust/compile/torture/bom_shebang.rs b/gcc/testsuite/rust/compile/torture/bom_shebang.rs new file mode 100644 index 00000000000..4c552e8d71d --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/bom_shebang.rs @@ -0,0 +1,2 @@ +#!/usr/bin/cat +pub fn main () { } diff --git a/gcc/testsuite/rust/compile/torture/bom_whitespace.rs b/gcc/testsuite/rust/compile/torture/bom_whitespace.rs new file mode 100644 index 00000000000..b10d5654473 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/bom_whitespace.rs @@ -0,0 +1,2 @@ + +pub fn main () { } diff --git a/gcc/testsuite/rust/compile/torture/bools_eq.rs b/gcc/testsuite/rust/compile/torture/bools_eq.rs new file mode 100644 index 00000000000..965127b5d54 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/bools_eq.rs @@ -0,0 +1,18 @@ +extern "C" +{ + fn abort (); +} + +fn beq (a: bool, b: bool) -> bool +{ + let bools_eq = a == b; + bools_eq +} + +pub fn main () +{ + let a = true; + let b = false; + let r = beq (a, b); + if r { unsafe { abort (); } } +} diff --git a/gcc/testsuite/rust/compile/torture/borrow1.rs b/gcc/testsuite/rust/compile/torture/borrow1.rs new file mode 100644 index 00000000000..8afa4746fef --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/borrow1.rs @@ -0,0 +1,17 @@ +fn main() { + let a: i32; + a = 123; + + let b: &i32; + b = &a; + + let aa; + aa = 456; + let bb: &_; + bb = &a; + + let aaa; + aaa = 123; + let bbb; + bbb = &aaa; +} diff --git a/gcc/testsuite/rust/compile/torture/borrow_function.rs b/gcc/testsuite/rust/compile/torture/borrow_function.rs new file mode 100644 index 00000000000..98c6f99683e --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/borrow_function.rs @@ -0,0 +1,5 @@ +fn foo() {} + +fn main() { + let _a = &foo; +} \ No newline at end of file diff --git a/gcc/testsuite/rust/compile/torture/break_function.rs b/gcc/testsuite/rust/compile/torture/break_function.rs new file mode 100644 index 00000000000..043e91c9502 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/break_function.rs @@ -0,0 +1,10 @@ +fn foo() -> i32 { + 1 +} + +fn main() { + let _a = loop { + break foo(); + }; +} + \ No newline at end of file diff --git a/gcc/testsuite/rust/compile/torture/byte_char_str.rs b/gcc/testsuite/rust/compile/torture/byte_char_str.rs new file mode 100644 index 00000000000..bc3ec5014e8 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/byte_char_str.rs @@ -0,0 +1,8 @@ +pub fn main () +{ + let _c = 'x'; + let _bc = b'x'; + + let _s = "abc"; + let _bs = b"abc"; +} diff --git a/gcc/testsuite/rust/compile/torture/byte_str.rs b/gcc/testsuite/rust/compile/torture/byte_str.rs new file mode 100644 index 00000000000..28934d2581d --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/byte_str.rs @@ -0,0 +1,4 @@ +pub fn main() { + let a: &[u8; 4]; + a = b"test"; +} diff --git a/gcc/testsuite/rust/compile/torture/cast1.rs b/gcc/testsuite/rust/compile/torture/cast1.rs new file mode 100644 index 00000000000..845d08cea01 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/cast1.rs @@ -0,0 +1,5 @@ +fn main() { + let a: *const i32 = &123; + let b: *mut i32 = (a as *mut i32); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/cast2.rs b/gcc/testsuite/rust/compile/torture/cast2.rs new file mode 100644 index 00000000000..82925e93271 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/cast2.rs @@ -0,0 +1,5 @@ +fn main() { + let a: i32 = 123i32; + let b: u8 = a as u8; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/cast3.rs b/gcc/testsuite/rust/compile/torture/cast3.rs new file mode 100644 index 00000000000..1de95687039 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/cast3.rs @@ -0,0 +1,6 @@ +fn main() { + let a = "foo\0"; + let b = a as *const str; + let c = b as *const i8; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/cfg_attr.rs b/gcc/testsuite/rust/compile/torture/cfg_attr.rs new file mode 100644 index 00000000000..d65faf2972a --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/cfg_attr.rs @@ -0,0 +1,7 @@ +mod fake {} // Add one line so gccrs doesn't believe we're parsing a shebang + +#[cfg_attr(feature = "somefeature", attribute = "someattr")] +struct Feature; +// { dg-warning "struct is never constructed" "" { target *-*-* } .-1 } + +fn main() {} diff --git a/gcc/testsuite/rust/compile/torture/char1.rs b/gcc/testsuite/rust/compile/torture/char1.rs new file mode 100644 index 00000000000..73835c218a2 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/char1.rs @@ -0,0 +1,4 @@ +fn main() { + let a; + a = 'c'; +} diff --git a/gcc/testsuite/rust/compile/torture/check-doc-attr-string.rs b/gcc/testsuite/rust/compile/torture/check-doc-attr-string.rs new file mode 100644 index 00000000000..e113120bdbc --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/check-doc-attr-string.rs @@ -0,0 +1,18 @@ +#![crate_type = "lib"] + +#[doc(alias = "foo")] // ok! +#[doc(alias("bar", "baz"))] // ok! +pub struct Bar; + +#[doc(alias = " +")] // { dg-error "invalid character used" "" { target *-*-* } .-1 } +pub struct Foo; + +#[doc(alias( + " +" +))] // ko but unchecked for now +pub struct Foo2; + +#[doc(whatever = "buidule")] // ko as well but unchecked for now +struct Boo; diff --git a/gcc/testsuite/rust/compile/torture/coercion1.rs b/gcc/testsuite/rust/compile/torture/coercion1.rs new file mode 100644 index 00000000000..3bfa938ffdc --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/coercion1.rs @@ -0,0 +1,11 @@ +pub fn main() { + let a: &i32 = &123; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let b: &mut i32 = &mut 123; + + let c: &i32 = &mut 123; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let d: &i32 = b; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/coercion2.rs b/gcc/testsuite/rust/compile/torture/coercion2.rs new file mode 100644 index 00000000000..127f257f8b6 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/coercion2.rs @@ -0,0 +1,20 @@ +pub fn main() { + let a: *const i32 = &123; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let b: &i32 = &123; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let c: &mut i32 = &mut 123; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let d: *mut i32 = &mut 123; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let e: &i32 = &mut 123; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let f: *const i32 = &mut 123; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let g = &123; + let h: *const i32 = g; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/comparison_expr1.rs b/gcc/testsuite/rust/compile/torture/comparison_expr1.rs new file mode 100644 index 00000000000..ed71ec89025 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/comparison_expr1.rs @@ -0,0 +1,38 @@ +fn is_zero(x: i32) -> bool { + x == 0 +} + +fn is_not_zero(x: i32) -> bool { + x != 0 +} + +fn is_positive(x: i32) -> bool { + x > 0 +} + +fn is_negative(x: i32) -> bool { + x < 0 +} + +fn is_positive_or_zero(x: i32) -> bool { + x >= 0 +} + +fn is_negative_or_zero(x: i32) -> bool { + x <= 0 +} + +fn main() { + let a: bool = is_zero(1); + let b: bool = is_not_zero(2); + let c: bool = is_positive(3); + let d: bool = is_negative(4); + let e: bool = is_positive_or_zero(5); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let f: bool = is_negative_or_zero(6); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let g: bool = a || b; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let h: bool = c && d; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/compile.exp b/gcc/testsuite/rust/compile/torture/compile.exp new file mode 100644 index 00000000000..48da264a47a --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/compile.exp @@ -0,0 +1,33 @@ +# Copyright (C) 2021-2022 Free Software Foundation, Inc. + +# This program 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 of the License, or +# (at your option) any later version. +# +# This program 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 +# . + +# Compile tests, torture testing. + +# Load support procs. +load_lib rust-dg.exp + +# Initialize `dg'. +dg-init + +# Main loop. +set saved-dg-do-what-default ${dg-do-what-default} + +set dg-do-what-default "compile" +gcc-dg-runtest [lsort [glob -nocomplain $srcdir/$subdir/*.rs]] "" "" +set dg-do-what-default ${saved-dg-do-what-default} + +# All done. +dg-finish diff --git a/gcc/testsuite/rust/compile/torture/compound_assignment_expr1.rs b/gcc/testsuite/rust/compile/torture/compound_assignment_expr1.rs new file mode 100644 index 00000000000..1ff0d24cf8e --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/compound_assignment_expr1.rs @@ -0,0 +1,23 @@ +fn main() { + let mut a = 1; + let mut b = 2; + let mut c = 3; + let mut d = 4; + let mut e = 5; + let mut f = 6; + let mut g = 7; + let mut h = 8; + let mut i = 9; + let mut j = 10; + + a += 1; + b -= 2; + c *= 3; + d /= 4; + e %= 5; + f &= 6; + g |= 7; + h ^= 8; + i <<= 9; + j >>= 10; +} diff --git a/gcc/testsuite/rust/compile/torture/conditional.rs b/gcc/testsuite/rust/compile/torture/conditional.rs new file mode 100644 index 00000000000..2bb3a95f033 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/conditional.rs @@ -0,0 +1,11 @@ +fn main() { + let mut x = 5; + + if x == 5 { + x = 1; + } else if x == 3 { + x = 2; + } else { + x = 3; + } +} diff --git a/gcc/testsuite/rust/compile/torture/constant1.rs b/gcc/testsuite/rust/compile/torture/constant1.rs new file mode 100644 index 00000000000..57bcb0b4970 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/constant1.rs @@ -0,0 +1,9 @@ +const TEST_CONST:i32 = 10; + +fn main() { + let mut x = TEST_CONST; + x = x + 1; + + let mut y = x + TEST_CONST; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/constant2.rs b/gcc/testsuite/rust/compile/torture/constant2.rs new file mode 100644 index 00000000000..d06324e8e65 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/constant2.rs @@ -0,0 +1,6 @@ +fn main() { + const C: usize = 42; + + let _a = C; + let _b: [i32; C] = [0; C]; +} diff --git a/gcc/testsuite/rust/compile/torture/constant3.rs b/gcc/testsuite/rust/compile/torture/constant3.rs new file mode 100644 index 00000000000..d2f1dd5b6db --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/constant3.rs @@ -0,0 +1,10 @@ +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; +} diff --git a/gcc/testsuite/rust/compile/torture/deadcode1.rs b/gcc/testsuite/rust/compile/torture/deadcode1.rs new file mode 100644 index 00000000000..1ba646f5c56 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/deadcode1.rs @@ -0,0 +1,22 @@ +fn test1() -> i32 { + return 2; + // { dg-warning "unreachable expression" "" { target *-*-* } .+1 } + 1 +} + +fn test2(x: i32) -> i32 { + if x > 1 { + return 5; + } else { + return 0; + } + // { dg-warning "unreachable statement" "" { target *-*-* } .+1 } + return 1; +} + +fn main() { + let call1 = test1(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let call2 = test2(2); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/deadcode2.rs b/gcc/testsuite/rust/compile/torture/deadcode2.rs new file mode 100644 index 00000000000..ba7d5f015e9 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/deadcode2.rs @@ -0,0 +1,10 @@ +fn foo() -> i32 { + return 1; + + let a = -1; // { dg-warning "unreachable statement" } + a // { dg-warning "unreachable expression" } +} + +fn main() { + foo(); +} diff --git a/gcc/testsuite/rust/compile/torture/deref1.rs b/gcc/testsuite/rust/compile/torture/deref1.rs new file mode 100644 index 00000000000..d715ce96c79 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/deref1.rs @@ -0,0 +1,6 @@ +fn main() { + let a = 123; + let b = &a; + let c = *b; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/deref_function.rs b/gcc/testsuite/rust/compile/torture/deref_function.rs new file mode 100644 index 00000000000..b1c5ff63423 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/deref_function.rs @@ -0,0 +1,10 @@ +fn foo() {} + + +fn main() { + let _c = *{ + let _a = foo; + let b = &1; + b + }; +} \ No newline at end of file diff --git a/gcc/testsuite/rust/compile/torture/doc_comment.rs b/gcc/testsuite/rust/compile/torture/doc_comment.rs new file mode 100644 index 00000000000..f99e41524ae --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/doc_comment.rs @@ -0,0 +1,16 @@ +/// doc comment 1 +/// doc comment 2 +/// `blah blah` markdown +pub struct TestStruct {} + +#[doc(hidden)] +pub struct DocAttribute {} + +#[doc(a,b)] +pub struct UnkAttribute {} + +fn main() { + let _ = TestStruct {}; + let _ = DocAttribute {}; + let _ = UnkAttribute {}; +} diff --git a/gcc/testsuite/rust/compile/torture/enum1.rs b/gcc/testsuite/rust/compile/torture/enum1.rs new file mode 100644 index 00000000000..7cea48f29e2 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/enum1.rs @@ -0,0 +1,13 @@ +enum Foo { + A, + B, + C(char), + D { x: i64, y: i64 }, +} + +fn main() { + let _a = Foo::A; + let _b = Foo::B; + let _c = Foo::C('x'); + let _d = Foo::D { x: 20, y: 80 }; +} diff --git a/gcc/testsuite/rust/compile/torture/extern_mod1.rs b/gcc/testsuite/rust/compile/torture/extern_mod1.rs new file mode 100644 index 00000000000..4b576e03d80 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/extern_mod1.rs @@ -0,0 +1,6 @@ +// { dg-additional-options "-w" } +mod modules; + +fn main() { + let twelve = modules::return_12(); +} diff --git a/gcc/testsuite/rust/compile/torture/extern_mod2.rs b/gcc/testsuite/rust/compile/torture/extern_mod2.rs new file mode 100644 index 00000000000..4984d5dc2c1 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/extern_mod2.rs @@ -0,0 +1,23 @@ +// { dg-additional-options "-w" } + +#[path = "modules/valid_path.rs"] +mod not_a_valid_path; + +#[path ="modules/valid_path.rs"] +mod path_without_extra_equal; + +#[path= "modules/valid_path.rs"] +mod no_leading_equal; + +#[path = "modules/valid_path.rs"] +mod extra_spaces; + +#[path] // { dg-error "path attributes must contain a filename" } +mod error; // { dg-error "no candidate found" } + +// This is "valid", and should only error out when parsing +// the file +#[path = "not_a_valid_file.rs"] +mod another_error; // { dg-error "No such file or directory" } + +fn main() {} diff --git a/gcc/testsuite/rust/compile/torture/float1.rs b/gcc/testsuite/rust/compile/torture/float1.rs new file mode 100644 index 00000000000..fbe89382267 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/float1.rs @@ -0,0 +1,9 @@ +fn test(x: f32) -> f32 { + return x + 1.0; +} + +fn main() { + let a_float = 5.123; + let call_test = test(a_float + 1.0); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/float_types.rs b/gcc/testsuite/rust/compile/torture/float_types.rs new file mode 100644 index 00000000000..7d3d298a1bb --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/float_types.rs @@ -0,0 +1,13 @@ +// { dg-prune-output "warning: unused name" } as there are many of these expected. + +fn main() { + let a1: f32 = 1.0f32; + let a2: f64 = 2.0f64; + let a3: f32 = 3f32; + let a4: f64 = 4f64; + + let b1 = 1.0f32; + let b2 = 2.0f64; + let b3 = 3f32; + let b4 = 4f64; +} diff --git a/gcc/testsuite/rust/compile/torture/forward_decl_1.rs b/gcc/testsuite/rust/compile/torture/forward_decl_1.rs new file mode 100644 index 00000000000..b8403f9b97f --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/forward_decl_1.rs @@ -0,0 +1,11 @@ +fn main() { + let mut an_integer = 5; + an_integer = test(1) + 3; + + let call_test = test(1); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} + +fn test(x: i32) -> i32 { + return x + 1; +} diff --git a/gcc/testsuite/rust/compile/torture/forward_decl_2.rs b/gcc/testsuite/rust/compile/torture/forward_decl_2.rs new file mode 100644 index 00000000000..efc3b0dc565 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/forward_decl_2.rs @@ -0,0 +1,6 @@ +fn main() { + let y = x + 1; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} + +static x: i32 = 3; diff --git a/gcc/testsuite/rust/compile/torture/forward_decl_3-unsafe.rs b/gcc/testsuite/rust/compile/torture/forward_decl_3-unsafe.rs new file mode 100644 index 00000000000..04935864f02 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/forward_decl_3-unsafe.rs @@ -0,0 +1,13 @@ +fn main() { + unsafe { + let struct_test = Foo { one: 1, two: 2 }; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + }; +} + +struct Foo { + one: i32, + // { dg-warning "field is never read" "" { target *-*-* } .-1 } + two: i32, + // { dg-warning "field is never read" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/forward_decl_3.rs b/gcc/testsuite/rust/compile/torture/forward_decl_3.rs new file mode 100644 index 00000000000..9256df5f728 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/forward_decl_3.rs @@ -0,0 +1,11 @@ +fn main() { + let struct_test = Foo { one: 1, two: 2 }; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} + +struct Foo { + one: i32, + // { dg-warning "field is never read" "" { target *-*-* } .-1 } + two: i32, + // { dg-warning "field is never read" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/forward_decl_4.rs b/gcc/testsuite/rust/compile/torture/forward_decl_4.rs new file mode 100644 index 00000000000..e1fe51f9025 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/forward_decl_4.rs @@ -0,0 +1,9 @@ +fn main() { + let mut x = TEST_CONST; + x = x + 1; + + let mut y = x + TEST_CONST; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} + +const TEST_CONST: i32 = 10; diff --git a/gcc/testsuite/rust/compile/torture/forward_decl_5.rs b/gcc/testsuite/rust/compile/torture/forward_decl_5.rs new file mode 100644 index 00000000000..73a47fe061b --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/forward_decl_5.rs @@ -0,0 +1,19 @@ +pub fn main() { + let a; + a = foo { a: 123, b: 456f32 }; + + let mut a = 123; + a = bar(a); + + let mut b = 456f32; + b = bar(b); + + fn bar(x: T) -> T { + x + } + + struct foo { + a: i32, + b: f32, + }; +} diff --git a/gcc/testsuite/rust/compile/torture/func1.rs b/gcc/testsuite/rust/compile/torture/func1.rs new file mode 100644 index 00000000000..df1789e7bbe --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/func1.rs @@ -0,0 +1,7 @@ +fn not_void() -> i32 { + 8 +} + +fn main() { + not_void(); +} diff --git a/gcc/testsuite/rust/compile/torture/func2.rs b/gcc/testsuite/rust/compile/torture/func2.rs new file mode 100644 index 00000000000..f7dd556d955 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/func2.rs @@ -0,0 +1,20 @@ +fn foo() { + 8; + 8; +} + +fn bar() -> i32 { + 8; + 8 +} + +fn baz() -> i32 { + 8; + return 8; +} + +fn main() { + let a = foo(); // { dg-warning "unused name" } + let b = bar(); // { dg-warning "unused name" } + let c = baz(); // { dg-warning "unused name" } +} diff --git a/gcc/testsuite/rust/compile/torture/function_reference1.rs b/gcc/testsuite/rust/compile/torture/function_reference1.rs new file mode 100644 index 00000000000..dfbd01bdbdc --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/function_reference1.rs @@ -0,0 +1,9 @@ +fn test(a: i32) -> i32 { + a + 1 +} + +fn main() { + let a = test; + let b = a(1); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/function_reference2.rs b/gcc/testsuite/rust/compile/torture/function_reference2.rs new file mode 100644 index 00000000000..3c3e7c10910 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/function_reference2.rs @@ -0,0 +1,9 @@ +fn test(a: i32) -> i32 { + a + 1 +} + +fn main() { + let a: fn(i32) -> i32 = test; + let b = a(1); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/function_reference3.rs b/gcc/testsuite/rust/compile/torture/function_reference3.rs new file mode 100644 index 00000000000..0cb3181f4a1 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/function_reference3.rs @@ -0,0 +1,20 @@ +struct Foo { + a: fn(i32) -> i32, + b: i32, +} + +fn test(a: i32) -> i32 { + a + 1 +} + +fn main() { + let a = test(1); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let b: fn(i32) -> i32 = test; + let c = b(1); + + let d = Foo { a: test, b: c }; + let e = (d.a)(d.b); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/function_reference4.rs b/gcc/testsuite/rust/compile/torture/function_reference4.rs new file mode 100644 index 00000000000..977e4c97215 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/function_reference4.rs @@ -0,0 +1,9 @@ +fn test(a: i32) -> i32 { + a + 1 +} + +fn main() { + let a: fn(_) -> _ = test; + let b = a(1); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/generics1.rs b/gcc/testsuite/rust/compile/torture/generics1.rs new file mode 100644 index 00000000000..87bcdc8f305 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics1.rs @@ -0,0 +1,51 @@ +struct Foo { + a: f32, + b: bool, +} + +struct GenericStruct { + a: T, + b: usize, +} + +fn main() { + let a1; + a1 = Foo { a: 1.0, b: false }; + + let b1: f32 = a1.a; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let c1: bool = a1.b; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let a2: GenericStruct; + a2 = GenericStruct:: { a: 1, b: 456 }; + + let b2: i8 = a2.a; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let c2: usize = a2.b; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let a3; + a3 = GenericStruct:: { a: 123, b: 456 }; + + let b3: i32 = a3.a; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let c3: usize = a3.b; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let a4; + a4 = GenericStruct { a: 1.0, b: 456 }; + + let b4: f32 = a4.a; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let c4: usize = a4.b; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let a5; + a5 = GenericStruct::<_> { a: true, b: 456 }; + + let b5: bool = a5.a; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let c5: usize = a5.b; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/generics10.rs b/gcc/testsuite/rust/compile/torture/generics10.rs new file mode 100644 index 00000000000..8473d49587b --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics10.rs @@ -0,0 +1,20 @@ +struct Foo(T); + +struct Bar { + a: Foo, + b: bool, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } +} + +fn test(a: Bar) -> Foo { + a.a +} + +fn main() { + let a: Bar = Bar:: { + a: Foo::(123), + b: true, + }; + let b: Foo = test(a); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/generics11.rs b/gcc/testsuite/rust/compile/torture/generics11.rs new file mode 100644 index 00000000000..3c8f5ba0058 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics11.rs @@ -0,0 +1,8 @@ +struct Foo(T, u32); + +type TypeAlias = Foo; + +fn main() { + let a: Foo; + a = TypeAlias { 0: 123, 1: 456 }; +} diff --git a/gcc/testsuite/rust/compile/torture/generics12.rs b/gcc/testsuite/rust/compile/torture/generics12.rs new file mode 100644 index 00000000000..f31be584e09 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics12.rs @@ -0,0 +1,17 @@ +struct GenericStruct(T, usize); + +impl GenericStruct { + fn new(a: i32, b: usize) -> Self { + GenericStruct(a, b) + } + + fn get(self) -> i32 { + self.0 + } +} + +fn main() { + let a: GenericStruct = GenericStruct::::new(123, 456); + let aa: i32 = a.get(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/generics13.rs b/gcc/testsuite/rust/compile/torture/generics13.rs new file mode 100644 index 00000000000..9eb598f02a8 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics13.rs @@ -0,0 +1,41 @@ +struct Foo { + a: A, + // { dg-warning "field is never read" "" { target *-*-* } .-1 } +} + +struct GenericStruct { + a: T, + b: usize, +} + +impl Foo { + fn test() -> i32 { + 123 + } + + fn bar(self) -> isize { + // { dg-warning "associated function is never used" "" { target *-*-* } .-1 } + self.a + } +} + +fn main() { + let a: i32 = Foo::test(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let a2: GenericStruct; + a2 = GenericStruct:: { a: 1, b: 456 }; + + let b2: i8 = a2.a; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let c2: usize = a2.b; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let a4; + a4 = GenericStruct { a: 1.0, b: 456 }; + + let b4: f32 = a4.a; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let c4: usize = a4.b; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/generics14.rs b/gcc/testsuite/rust/compile/torture/generics14.rs new file mode 100644 index 00000000000..e51a4079e30 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics14.rs @@ -0,0 +1,20 @@ +struct Foo { + a: A, + // { dg-warning "field is never read" "" { target *-*-* } .-1 } +} + +impl Foo { + fn test() -> i32 { + 123 + } + + fn bar(self) -> isize { + // { dg-warning "associated function is never used" "" { target *-*-* } .-1 } + self.a + } +} + +fn main() { + let a: i32 = Foo::test(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/generics15.rs b/gcc/testsuite/rust/compile/torture/generics15.rs new file mode 100644 index 00000000000..c16a67c4dd5 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics15.rs @@ -0,0 +1,23 @@ +struct Foo(T, bool); + +impl Foo { + fn bar(self) -> i32 { + self.0 + } +} + +impl Foo { + fn bar(self) -> f32 { + self.0 + } +} + +fn main() { + let a = Foo(123, true); + let aa = a.bar(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let b = Foo(456f32, true); + let bb = b.bar(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/generics16.rs b/gcc/testsuite/rust/compile/torture/generics16.rs new file mode 100644 index 00000000000..15b9d7b55e7 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics16.rs @@ -0,0 +1,31 @@ +struct Foo(T, bool); + +impl Foo { + fn new() -> Self { + Foo(123, true) + } + + fn bar(self) -> i32 { + self.0 + } +} + +impl Foo { + fn new() -> Self { + Foo(123f32, true) + } + + fn bar(self) -> f32 { + self.0 + } +} + +fn main() { + let a = Foo::::new(); + let aa: i32 = a.bar(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let b = Foo::::new(); + let bb: f32 = b.bar(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/generics17.rs b/gcc/testsuite/rust/compile/torture/generics17.rs new file mode 100644 index 00000000000..d52314999b9 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics17.rs @@ -0,0 +1,19 @@ +struct Foo(T); + +impl Foo { + fn new(a: X) -> Self { + Self(a) + } + + fn test(self) -> X { + self.0 + } +} + +fn main() { + let a; + a = Foo::new(123); + + let b = a.test(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/generics18.rs b/gcc/testsuite/rust/compile/torture/generics18.rs new file mode 100644 index 00000000000..4c98b86a1b9 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics18.rs @@ -0,0 +1,20 @@ +struct Foo(T); + +impl Foo { + fn new(a: X) -> Self { + // { dg-warning "associated function is never used" "" { target *-*-* } .-1 } + Self(a) + } + + fn test(self) -> X { + self.0 + } +} + +fn main() { + let a; + a = Foo(123); + + let b = a.test(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/generics19.rs b/gcc/testsuite/rust/compile/torture/generics19.rs new file mode 100644 index 00000000000..9a5b4cb48dc --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics19.rs @@ -0,0 +1,12 @@ +struct Foo(X, Y); + +impl Foo { + fn new(a: T) -> Self { + Self(123, a) + } +} + +fn main() { + let a; + a = Foo::new(false); +} diff --git a/gcc/testsuite/rust/compile/torture/generics2.rs b/gcc/testsuite/rust/compile/torture/generics2.rs new file mode 100644 index 00000000000..da0ab992243 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics2.rs @@ -0,0 +1,45 @@ +struct Foo(f32, bool); + +struct GenericStruct(T, usize); + +fn main() { + let a1; + a1 = Foo(1.0, false); + + let b1: f32 = a1.0; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let c1: bool = a1.1; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let a2: GenericStruct; + a2 = GenericStruct::(1, 456); + + let b2: i8 = a2.0; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let c2: usize = a2.1; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let a3; + a3 = GenericStruct::(123, 456); + + let b3: i32 = a3.0; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let c3: usize = a3.1; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let a4; + a4 = GenericStruct(1.0, 456); + + let b4: f32 = a4.0; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let c4: usize = a4.1; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let a5; + a5 = GenericStruct::<_>(true, 456); + + let b5: bool = a5.0; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let c5: usize = a5.1; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/generics20.rs b/gcc/testsuite/rust/compile/torture/generics20.rs new file mode 100644 index 00000000000..8fe1cffdf7d --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics20.rs @@ -0,0 +1,12 @@ +struct Foo(A, B); + +impl Foo { + fn new(a: T, b: T) -> Self { + Self(a, b) + } +} + +fn main() { + let a; + a = Foo::new(123, 456); +} diff --git a/gcc/testsuite/rust/compile/torture/generics21.rs b/gcc/testsuite/rust/compile/torture/generics21.rs new file mode 100644 index 00000000000..dc4e935cac7 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics21.rs @@ -0,0 +1,13 @@ +fn callee(t: &T) -> i32 { + // { dg-warning "unused name" "" { target *-*-* } .-1 } + 32 +} + +fn caller(t: i32) -> i32 { + callee(&t) +} + +fn main() { + let a; + a = caller(123); +} diff --git a/gcc/testsuite/rust/compile/torture/generics22.rs b/gcc/testsuite/rust/compile/torture/generics22.rs new file mode 100644 index 00000000000..465ebb0f5e1 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics22.rs @@ -0,0 +1,13 @@ +fn callee(t: (T, bool)) -> i32 { + // { dg-warning "unused name" "" { target *-*-* } .-1 } + 32 +} + +fn caller(t: i32) -> i32 { + callee((t, false)) +} + +fn main() { + let a; + a = caller(123); +} diff --git a/gcc/testsuite/rust/compile/torture/generics23.rs b/gcc/testsuite/rust/compile/torture/generics23.rs new file mode 100644 index 00000000000..2169e3649c6 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics23.rs @@ -0,0 +1,6 @@ +struct Foo(A); + +fn main() { + let a: Foo; + a = Foo(123f32); +} diff --git a/gcc/testsuite/rust/compile/torture/generics24.rs b/gcc/testsuite/rust/compile/torture/generics24.rs new file mode 100644 index 00000000000..0de45a8c404 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics24.rs @@ -0,0 +1,34 @@ +struct Foo { + a: A, +} + +impl Foo { + fn bar(self) -> isize { + self.a + } +} + +impl Foo { + fn bar(self) -> char { + // { dg-warning "associated function is never used" "" { target *-*-* } .-1 } + self.a + } +} + +impl Foo { + fn bar(self) { + let a: (isize, char) = self.a; + let b = a.0; + let c = a.1; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let aa: Foo = Foo { a: b }; + let bb: isize = aa.bar(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + } +} + +fn main() { + let a = Foo { a: (123, 'a') }; + a.bar(); +} diff --git a/gcc/testsuite/rust/compile/torture/generics25.rs b/gcc/testsuite/rust/compile/torture/generics25.rs new file mode 100644 index 00000000000..e7792e3efb3 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics25.rs @@ -0,0 +1,9 @@ +struct Foo(A, B); + +fn main() { + let a: Foo; + a = Foo::(true, (false, true)); + + let b: (bool, bool); + b = a.1; +} diff --git a/gcc/testsuite/rust/compile/torture/generics26.rs b/gcc/testsuite/rust/compile/torture/generics26.rs new file mode 100644 index 00000000000..522e16f32f7 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics26.rs @@ -0,0 +1,21 @@ +// github issue #415 +fn test(a: A, b: B) -> (A, B) { + (a, b) +} + +fn main() { + let a = test::(123, 456); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let b = test::(123f32, 456f32); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let c = test::<_, _>(123, 456f32); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let d = test(true, 1234); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let e = test((123, false), 123f32); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/generics27.rs b/gcc/testsuite/rust/compile/torture/generics27.rs new file mode 100644 index 00000000000..9871638dd9f --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics27.rs @@ -0,0 +1,16 @@ +// github issue #415 +fn test(a: &A) -> &A { + a +} + +fn main() { + let a = 123; + let b = &a; + let c = test(b); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let a = 123f32; + let b = &a; + let c = test(b); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/generics28.rs b/gcc/testsuite/rust/compile/torture/generics28.rs new file mode 100644 index 00000000000..8cee8b00fb2 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics28.rs @@ -0,0 +1,18 @@ +struct Foo(A, B); + +impl Foo { + fn test(a: X) -> X { + a + } +} + +fn main() { + let a; + a = Foo::test::<_>(123); + + let b; + b = Foo::test::(true); + + let c; + c = Foo::test(456f32); +} diff --git a/gcc/testsuite/rust/compile/torture/generics29.rs b/gcc/testsuite/rust/compile/torture/generics29.rs new file mode 100644 index 00000000000..e09a1044574 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics29.rs @@ -0,0 +1,16 @@ +struct Foo(A, B); + +impl Foo { + fn test(self, a: X) -> X { + // { dg-warning "unused name" "" { target *-*-* } .-1 } + a + } +} + +fn main() { + let a; + a = Foo(123, 456f32); + + let b; + b = a.test::(false); +} diff --git a/gcc/testsuite/rust/compile/torture/generics3.rs b/gcc/testsuite/rust/compile/torture/generics3.rs new file mode 100644 index 00000000000..ceec8f7d9c6 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics3.rs @@ -0,0 +1,15 @@ +fn test(a: T) -> T { + a +} + +fn main() { + let a; + a = test(123); + let aa: i32 = a; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let b; + b = test::(456); + let bb: u32 = b; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/generics30.rs b/gcc/testsuite/rust/compile/torture/generics30.rs new file mode 100644 index 00000000000..229f6d1254b --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics30.rs @@ -0,0 +1,16 @@ +struct Foo(A, B); + +impl Foo { + fn test(self, a: X) -> X { + // { dg-warning "unused name" "" { target *-*-* } .-1 } + a + } +} + +fn main() { + let a; + a = Foo(123, 456f32); + + let b; + b = a.test::(false); +} diff --git a/gcc/testsuite/rust/compile/torture/generics31.rs b/gcc/testsuite/rust/compile/torture/generics31.rs new file mode 100644 index 00000000000..68ad4bf9a96 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics31.rs @@ -0,0 +1,15 @@ +struct Foo(A, B); + +impl Foo { + fn test(self, a: X) -> (T, X) { + (self.0, a) + } +} + +fn main() { + let a; + a = Foo(123, 456f32); + + let b; + b = a.test::(false); +} diff --git a/gcc/testsuite/rust/compile/torture/generics32.rs b/gcc/testsuite/rust/compile/torture/generics32.rs new file mode 100644 index 00000000000..21b9cae7409 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics32.rs @@ -0,0 +1,15 @@ +struct Foo(A, B); + +impl Foo { + fn test(self, a: X) -> (T, X) { + (self.0, a) + } +} + +fn main() { + let a; + a = Foo(123, 456f32); + + let b; + b = a.test(false); +} diff --git a/gcc/testsuite/rust/compile/torture/generics4.rs b/gcc/testsuite/rust/compile/torture/generics4.rs new file mode 100644 index 00000000000..915cc49c68b --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics4.rs @@ -0,0 +1,17 @@ +struct Foo { + a: T, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } + b: bool, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } +} + +fn test(a: T) -> Foo { + Foo { a: a, b: true } +} + +fn main() { + let a: Foo = test(123); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let b: Foo = test(456); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/generics5.rs b/gcc/testsuite/rust/compile/torture/generics5.rs new file mode 100644 index 00000000000..b7f43028992 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics5.rs @@ -0,0 +1,10 @@ +fn test(a: T) -> T { + a +} + +fn main() { + let a: i32 = test(123); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let b: i32 = test(456); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/generics6.rs b/gcc/testsuite/rust/compile/torture/generics6.rs new file mode 100644 index 00000000000..5456b6dcb97 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics6.rs @@ -0,0 +1,16 @@ +struct Foo(T); + +struct Bar { + a: Foo, + b: bool, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } +} + +fn main() { + let a: Bar = Bar:: { + a: Foo::(123), + b: true, + }; + let b: i32 = a.a.0; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/generics7.rs b/gcc/testsuite/rust/compile/torture/generics7.rs new file mode 100644 index 00000000000..e8e5ca69c3d --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics7.rs @@ -0,0 +1,14 @@ +struct Foo(T); + +struct Bar { + a: Foo, + b: bool, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } +} + +fn main() { + let a = Foo::(123); + let b: Bar = Bar { a: a, b: true }; + let c: i32 = b.a.0; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/generics8.rs b/gcc/testsuite/rust/compile/torture/generics8.rs new file mode 100644 index 00000000000..036d85568f0 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics8.rs @@ -0,0 +1,18 @@ +struct GenericStruct(T, usize); + +impl GenericStruct { + fn new(a: T, b: usize) -> Self { + GenericStruct(a, b) + } +} + +fn main() { + let a: GenericStruct = GenericStruct::::new(123, 456); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let b: GenericStruct = GenericStruct::<_>::new(123, 456); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let c: GenericStruct = GenericStruct::new(123f32, 456); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/generics9.rs b/gcc/testsuite/rust/compile/torture/generics9.rs new file mode 100644 index 00000000000..307c34f3e9b --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/generics9.rs @@ -0,0 +1,25 @@ +struct GenericStruct(T, usize); + +impl GenericStruct { + fn new(a: T, b: usize) -> Self { + GenericStruct(a, b) + } + + fn get(self) -> T { + self.0 + } +} + +fn main() { + let a: GenericStruct = GenericStruct::::new(123, 456); + let aa: i32 = a.get(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let b: GenericStruct = GenericStruct::<_>::new(123, 456); + let bb: u32 = b.get(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let c: GenericStruct = GenericStruct::new(123f32, 456); + let cc: f32 = c.get(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/grouped_expr_function.rs b/gcc/testsuite/rust/compile/torture/grouped_expr_function.rs new file mode 100644 index 00000000000..eca7178b7f7 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/grouped_expr_function.rs @@ -0,0 +1,6 @@ +fn foo() {} + + +fn main() { + let _a = (foo()); +} \ No newline at end of file diff --git a/gcc/testsuite/rust/compile/torture/identifier-missing-impl-1.rs b/gcc/testsuite/rust/compile/torture/identifier-missing-impl-1.rs new file mode 100644 index 00000000000..2389fa52bfd --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/identifier-missing-impl-1.rs @@ -0,0 +1,19 @@ +struct I(); + +impl I { + fn () { + // { dg-error {expecting 'identifier' but '\(' found} "" { target *-*-* } .-1 } + // { dg-error {failed to parse inherent impl item in inherent impl} "" { target *-*-* } .-2 } + // { dg-error {failed to parse item in crate} "" { target *-*-* } .-3 } + } +} + +impl I { + unsafe fn () { + // { dg-error {expecting 'identifier' but '\(' found} "" { xfail *-*-* } .-1 } + } +} + +fn main() { + let _i = I(); +} diff --git a/gcc/testsuite/rust/compile/torture/if.rs b/gcc/testsuite/rust/compile/torture/if.rs new file mode 100644 index 00000000000..bcd520f66a9 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/if.rs @@ -0,0 +1,19 @@ +fn foo() -> bool { + true +} + +fn bar() {} + +struct Foo1 { + one: i32 +} + + +fn main() { + if foo() { + bar(); + let a = Foo1{one: 1}; + a.one + } + +} \ No newline at end of file diff --git a/gcc/testsuite/rust/compile/torture/if_elif.rs b/gcc/testsuite/rust/compile/torture/if_elif.rs new file mode 100644 index 00000000000..a89ad5eb02f --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/if_elif.rs @@ -0,0 +1,20 @@ +fn foo() -> bool { + true +} + +fn bar() -> bool { + false +} + +struct Foo1 { + one: i32 +} + + +fn main() { + if foo() { + } else if bar() { + let a = Foo1{one: 1}; + a.one; + } +} \ No newline at end of file diff --git a/gcc/testsuite/rust/compile/torture/if_elif_else_expr1.rs b/gcc/testsuite/rust/compile/torture/if_elif_else_expr1.rs new file mode 100644 index 00000000000..65ed7f7a23a --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/if_elif_else_expr1.rs @@ -0,0 +1,14 @@ +fn test(x: i32) -> i32 { + if x == 10 { + 123 + } else if x < 10 { + 456 + } else { + 789 + } +} + +fn main() { + let a = test(1); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/if_else.rs b/gcc/testsuite/rust/compile/torture/if_else.rs new file mode 100644 index 00000000000..09aecaed4d6 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/if_else.rs @@ -0,0 +1,19 @@ +fn foo() -> bool { + true +} + +fn bar() {} + +struct Foo1 { + one: i32 +} + + +fn main() { + if foo() { + bar(); + } else { + let a = Foo1{one: 1}; + a.one; + } +} \ No newline at end of file diff --git a/gcc/testsuite/rust/compile/torture/ifunaryexpr.rs b/gcc/testsuite/rust/compile/torture/ifunaryexpr.rs new file mode 100644 index 00000000000..8f0bb87f558 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/ifunaryexpr.rs @@ -0,0 +1,22 @@ +extern "C" +{ + pub fn abort (); +} + +struct B { b: bool } + +pub fn main () +{ + let n = 1; + if 0 > -n { } else { unsafe { abort (); } } + + let b = true; + if !b { unsafe { abort (); } } + if !!b { } else { unsafe { abort (); } } + + let bb = B { b: false }; + + if !bb.b && !b { unsafe { abort (); } } + + if (B { b: true }).b { } else { unsafe { abort (); } } +} diff --git a/gcc/testsuite/rust/compile/torture/impl_block1.rs b/gcc/testsuite/rust/compile/torture/impl_block1.rs new file mode 100644 index 00000000000..d67afa187b1 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/impl_block1.rs @@ -0,0 +1,23 @@ +struct Foo(i32, bool); + +impl Foo { + fn new(a: i32, b: bool) -> Foo { + Foo(a, b) + } + + fn test2() -> i32 { + test_forward_decl() + } +} + +fn test_forward_decl() -> i32 { + 123 +} + +fn main() { + let a; + a = Foo::new(1, true); + + let b; + b = Foo::test2(); +} diff --git a/gcc/testsuite/rust/compile/torture/impl_block2.rs b/gcc/testsuite/rust/compile/torture/impl_block2.rs new file mode 100644 index 00000000000..0ed592d07be --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/impl_block2.rs @@ -0,0 +1,28 @@ +struct Foo(i32, bool); + +impl Foo { + const number: i32 = 456; + + fn new(a: i32, b: bool) -> Foo { + Foo(a, b) + } + + fn test2() -> i32 { + test_forward_decl() + } +} + +fn test_forward_decl() -> i32 { + 123 +} + +fn main() { + let a; + a = Foo::new(1, true); + + let b; + b = Foo::test2(); + + let c; + c = Foo::new(Foo::number, true); +} diff --git a/gcc/testsuite/rust/compile/torture/impl_block3.rs b/gcc/testsuite/rust/compile/torture/impl_block3.rs new file mode 100644 index 00000000000..22ce19f704d --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/impl_block3.rs @@ -0,0 +1,36 @@ +struct Point { + x: f64, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } + y: f64, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } +} + +impl Point { + fn origin() -> Point { + Point { x: 0.0, y: 0.0 } + } + + fn new(x: f64, y: f64) -> Point { + Point { x: x, y: y } + } +} + +struct Rectangle { + p1: Point, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } + p2: Point, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } +} + +impl Rectangle { + fn from(p1: Point, p2: Point) -> Self { + Self { p1, p2 } + } +} + +fn main() { + let p1 = Point::origin(); + let p2 = Point::new(3.0, 4.0); + let rect = Rectangle::from(p1, p2); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/impl_block_unused.rs b/gcc/testsuite/rust/compile/torture/impl_block_unused.rs new file mode 100644 index 00000000000..fea86319243 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/impl_block_unused.rs @@ -0,0 +1,17 @@ +struct Foo(i32, bool); + +impl Foo { + fn new(a: i32, b: bool) -> Foo { + // { dg-warning "associated function is never used" "" { target *-*-* } .-1 } + Foo(a, b) + } + + fn test2() -> i32 { + // { dg-warning "associated function is never used" "" { target *-*-* } .-1 } + 1 + } +} + +fn main() { + let _a = Foo(1, true); +} diff --git a/gcc/testsuite/rust/compile/torture/implicit_returns1.rs b/gcc/testsuite/rust/compile/torture/implicit_returns1.rs new file mode 100644 index 00000000000..54cc8b3aea8 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/implicit_returns1.rs @@ -0,0 +1,73 @@ +fn test1() -> i32 { + 1 +} + +fn test2() -> i32 { + return 2; +} + +fn test3(x: i32) -> i32 { + if x > 1 { + 5 + } else { + 0 + } +} + +fn test4(x: i32) -> i32 { + if x > 1 { + return 1; + } + 0 +} + +fn test5(x: i32) -> i32 { + if x > 1 { + if x == 5 { + 7 + } else { + 9 + } + } else { + 0 + } +} + +fn test6(x: i32) -> i32 { + if x > 1 { + return 5; + } else { + return 0; + } +} + +fn test7(x: i32) -> i32 { + if x > 1 { + return 5; + } else { + return 0; + } +} + +fn test8() -> i32 { + return 1; +} + +fn main() { + let call1 = test1(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let call2 = test2(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let call3 = test3(3); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let call4 = test4(4); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let call5 = test5(5); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let call6 = test6(6); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let call7 = test7(7); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let call8 = test8(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/infer_type1.rs b/gcc/testsuite/rust/compile/torture/infer_type1.rs new file mode 100644 index 00000000000..aabfcef895b --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/infer_type1.rs @@ -0,0 +1,4 @@ +fn main() { + let array: [_; 2] = [111, 222]; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/inner_attributes.rs b/gcc/testsuite/rust/compile/torture/inner_attributes.rs new file mode 100644 index 00000000000..3410dd6ec87 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/inner_attributes.rs @@ -0,0 +1,3 @@ +#![allow(dead_code)] +#![allow(unused_variables)] +pub fn main () { } diff --git a/gcc/testsuite/rust/compile/torture/integer_inference_var1.rs b/gcc/testsuite/rust/compile/torture/integer_inference_var1.rs new file mode 100644 index 00000000000..ccee06aad10 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/integer_inference_var1.rs @@ -0,0 +1,6 @@ +const TEST_CONST: i32 = 10; + +fn main() { + let a; + a = TEST_CONST; +} diff --git a/gcc/testsuite/rust/compile/torture/integer_inference_var2.rs b/gcc/testsuite/rust/compile/torture/integer_inference_var2.rs new file mode 100644 index 00000000000..2209e937479 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/integer_inference_var2.rs @@ -0,0 +1,6 @@ +fn main() { + let a = 1u32; + + let b; + b = a; +} diff --git a/gcc/testsuite/rust/compile/torture/integer_inference_var3.rs b/gcc/testsuite/rust/compile/torture/integer_inference_var3.rs new file mode 100644 index 00000000000..582ae77caa4 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/integer_inference_var3.rs @@ -0,0 +1,11 @@ +fn test(a: u32) -> u32 { + a + 1 +} + +fn main() { + let param; + param = 123; + + let a = test(param); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/integer_inference_var4.rs b/gcc/testsuite/rust/compile/torture/integer_inference_var4.rs new file mode 100644 index 00000000000..136d8183d08 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/integer_inference_var4.rs @@ -0,0 +1,4 @@ +fn main() { + let a; + a = 1; +} diff --git a/gcc/testsuite/rust/compile/torture/integer_inference_var5.rs b/gcc/testsuite/rust/compile/torture/integer_inference_var5.rs new file mode 100644 index 00000000000..051de1d6520 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/integer_inference_var5.rs @@ -0,0 +1,25 @@ +const TEST_CONST: i32 = 10; + +fn test(x: u32) -> u32 { + x + 1 +} + +fn main() { + let x = TEST_CONST; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let a = 1u32; + let b = a; + + let c; + c = 1; + + let d; + d = b; + + let param; + param = 123; + + let test_call = test(param); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/integer_types.rs b/gcc/testsuite/rust/compile/torture/integer_types.rs new file mode 100644 index 00000000000..95a73780bb1 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/integer_types.rs @@ -0,0 +1,27 @@ +// { dg-prune-output "warning: unused name" } as there are many of these expected. + +fn main() { + let a1: i8 = 1i8; + let a2: i16 = 2i16; + let a3: i32 = 3i32; + let a4: i64 = 4i64; + let a5: i128 = 5i128; + + let b1 = 1i8; + let b2 = 2i16; + let b3 = 3i32; + let b4 = 4i64; + let b5 = 5i128; + + let c1: u8 = 1u8; + let c2: u16 = 2u16; + let c3: u32 = 3u32; + let c4: u64 = 4u64; + let c5: u128 = 5u128; + + let d1 = 1u8; + let d2 = 2u16; + let d3 = 3u32; + let d4 = 4u64; + let d5 = 5u128; +} diff --git a/gcc/testsuite/rust/compile/torture/intrinsics-1.rs b/gcc/testsuite/rust/compile/torture/intrinsics-1.rs new file mode 100644 index 00000000000..6704c0210d1 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/intrinsics-1.rs @@ -0,0 +1,22 @@ +// { dg-additional-options -fdump-tree-original } + +#![feature(intrinsics)] + +extern "rust-intrinsic" { + pub fn sqrtf32(x: f32) -> f32; + pub fn sinf32(x: f32) -> f32; +} + +fn main() { + unsafe fn foo() { + let mut f32; + + f32 = sqrtf32(5f32); + // { dg-final { scan-tree-dump-times {(?n)f32 = __builtin_sqrtf \(5\.0e\+0\);$} 1 original } } + + f32 = sinf32(39f32); + // { dg-final { scan-tree-dump-times {(?n)f32 = __builtin_sinf \(3\.9e\+1\);$} 1 original } } + } + + unsafe { foo() }; +} diff --git a/gcc/testsuite/rust/compile/torture/intrinsics-2.rs b/gcc/testsuite/rust/compile/torture/intrinsics-2.rs new file mode 100644 index 00000000000..6b2339f38f3 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/intrinsics-2.rs @@ -0,0 +1,22 @@ +// { dg-additional-options -fdump-tree-original } + +#![feature(intrinsics)] + +extern "rust-intrinsic" { + pub fn size_of() -> usize; +} + +fn main() -> i32 { + unsafe fn foo() -> usize { + let f: f32; + + let s_f32 = size_of::(); + let s_f64 = size_of::(); + let s_f32_again = size_of::(); + + s_f32 + s_f64 + s_f32_again + } + + // useless code, just used for function compilation caching + unsafe { foo() as i32 } +} diff --git a/gcc/testsuite/rust/compile/torture/isolated_cr_block_comment.rs b/gcc/testsuite/rust/compile/torture/isolated_cr_block_comment.rs new file mode 100644 index 00000000000..9a1e090f330 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/isolated_cr_block_comment.rs @@ -0,0 +1,2 @@ +/* comment cr is allowed */ +pub fn main () { } diff --git a/gcc/testsuite/rust/compile/torture/isolated_cr_line_comment.rs b/gcc/testsuite/rust/compile/torture/isolated_cr_line_comment.rs new file mode 100644 index 00000000000..4e921a225c2 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/isolated_cr_line_comment.rs @@ -0,0 +1,2 @@ +// comment cr is allowed +pub fn main () { } diff --git a/gcc/testsuite/rust/compile/torture/issue-1024.rs b/gcc/testsuite/rust/compile/torture/issue-1024.rs new file mode 100644 index 00000000000..109540934a8 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/issue-1024.rs @@ -0,0 +1,11 @@ +extern "rust-intrinsic" { + pub fn size_of() -> usize; +} + +fn test() -> usize { + unsafe { size_of::() } +} + +fn main() { + let _a = test(); +} diff --git a/gcc/testsuite/rust/compile/torture/issue-1075.rs b/gcc/testsuite/rust/compile/torture/issue-1075.rs new file mode 100644 index 00000000000..7c0a0434262 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/issue-1075.rs @@ -0,0 +1,42 @@ +// { dg-additional-options "-w" } +extern "rust-intrinsic" { + #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")] + pub fn offset(dst: *const T, offset: isize) -> *const T; +} + +struct FatPtr { + data: *const T, + len: usize, +} + +union Repr { + rust: *const [T], + rust_mut: *mut [T], + raw: FatPtr, +} + +impl *const [T] { + pub const fn len(self) -> usize { + // SAFETY: this is safe because `*const [T]` and `FatPtr` have the same layout. + // Only `std` can make this guarantee. + unsafe { Repr { rust: self }.raw.len } + } + + pub const fn as_ptr(self) -> *const T { + self as *const T + } +} + +impl *const T { + pub const unsafe fn offset(self, count: isize) -> *const T { + unsafe { offset(self, count) } + } + + pub const unsafe fn add(self, count: usize) -> Self { + unsafe { self.offset(count as isize) } + } + + pub const fn as_ptr(self) -> *const T { + self as *const T + } +} diff --git a/gcc/testsuite/rust/compile/torture/issue-1432.rs b/gcc/testsuite/rust/compile/torture/issue-1432.rs new file mode 100644 index 00000000000..083a369d16f --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/issue-1432.rs @@ -0,0 +1,77 @@ +// { dg-additional-options "-w" } +mod intrinsics { + extern "rust-intrinsic" { + #[rustc_const_stable(feature = "const_int_wrapping", since = "1.40.0")] + pub fn wrapping_add(a: T, b: T) -> T; + #[rustc_const_stable(feature = "const_int_rotate", since = "1.40.0")] + pub fn rotate_left(a: T, b: T) -> T; + #[rustc_const_stable(feature = "const_int_rotate", since = "1.40.0")] + pub fn rotate_right(a: T, b: T) -> T; + #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")] + pub fn offset(ptr: *const T, count: isize) -> *const T; + } +} + +mod mem { + extern "rust-intrinsic" { + #[rustc_const_stable(feature = "const_transmute", since = "1.46.0")] + fn transmute(_: T) -> U; + #[rustc_const_stable(feature = "const_size_of", since = "1.40.0")] + fn size_of() -> usize; + } +} + +macro_rules! impl_uint { + ($($ty:ident = $lang:literal),*) => { + $( + impl $ty { + pub fn wrapping_add(self, rhs: Self) -> Self { + // intrinsics::wrapping_add(self, rhs) + self + rhs + } + + pub fn rotate_left(self, n: u32) -> Self { + unsafe { + intrinsics::rotate_left(self, n as Self) + } + } + + pub fn rotate_right(self, n: u32) -> Self { + unsafe { + intrinsics::rotate_right(self, n as Self) + } + } + + pub fn to_le(self) -> Self { + #[cfg(target_endian = "little")] + { + self + } + } + + pub const fn from_le_bytes(bytes: [u8; mem::size_of::()]) -> Self { + Self::from_le(Self::from_ne_bytes(bytes)) + } + + pub const fn from_le(x: Self) -> Self { + #[cfg(target_endian = "little")] + { + x + } + } + + pub const fn from_ne_bytes(bytes: [u8; mem::size_of::()]) -> Self { + unsafe { mem::transmute(bytes) } + } + } + )* + } +} + +impl_uint!( + u8 = "u8", + u16 = "u16", + u32 = "u32", + u64 = "u64", + usize = "usize" +); diff --git a/gcc/testsuite/rust/compile/torture/issue-1434.rs b/gcc/testsuite/rust/compile/torture/issue-1434.rs new file mode 100644 index 00000000000..dc000e942e6 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/issue-1434.rs @@ -0,0 +1,53 @@ +// { dg-options "-w" } +const BLOCK_LEN: usize = 64; + +const IV: [u32; 8] = [ + 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19, +]; + +struct ChunkState { + chaining_value: [u32; 8], + chunk_counter: u64, + block: [u8; BLOCK_LEN], + block_len: u8, + blocks_compressed: u8, + flags: u32, +} + +impl ChunkState { + fn new(key_words: [u32; 8], chunk_counter: u64, flags: u32) -> Self { + Self { + chaining_value: key_words, + chunk_counter, + block: [0; BLOCK_LEN], + block_len: 0, + blocks_compressed: 0, + flags, + } + } +} + +pub struct Hasher { + chunk_state: ChunkState, + key_words: [u32; 8], + cv_stack: [[u32; 8]; 54], // Space for 54 subtree chaining values: + cv_stack_len: u8, // 2^54 * CHUNK_LEN = 2^64 + flags: u32, +} + +impl Hasher { + fn new_internal(key_words: [u32; 8], flags: u32) -> Self { + Self { + chunk_state: ChunkState::new(key_words, 0, flags), + key_words, + cv_stack: [[0; 8]; 54], + cv_stack_len: 0, + flags, + } + } + + /// Construct a new `Hasher` for the regular hash function. + pub fn new() -> Self { + Self::new_internal(IV, 0) + } +} diff --git a/gcc/testsuite/rust/compile/torture/issue-368.rs b/gcc/testsuite/rust/compile/torture/issue-368.rs new file mode 100644 index 00000000000..18bc9bdc62e --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/issue-368.rs @@ -0,0 +1,9 @@ +struct S; + +fn foo(s: S) -> S { + s +} + +fn main() { + let _s: S = foo(S); +} diff --git a/gcc/testsuite/rust/compile/torture/issue-808.rs b/gcc/testsuite/rust/compile/torture/issue-808.rs new file mode 100644 index 00000000000..2e5a81fe516 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/issue-808.rs @@ -0,0 +1,20 @@ +pub trait Foo { + type Target; + + fn bar(&self) -> &Self::Target; +} + +impl Foo for &T { + type Target = T; + + fn bar(&self) -> &T { + *self + } +} + +pub fn main() { + let a: i32 = 123; + let b: &i32 = &a; + + b.bar(); +} diff --git a/gcc/testsuite/rust/compile/torture/issue-862.rs b/gcc/testsuite/rust/compile/torture/issue-862.rs new file mode 100644 index 00000000000..c1a4609ba86 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/issue-862.rs @@ -0,0 +1,74 @@ +// { dg-additional-options "-w" } +extern "C" { + fn printf(s: *const i8, ...); +} + +#[lang = "deref"] +pub trait Deref { + type Target; + + fn deref(&self) -> &Self::Target; +} + +impl Deref for &T { + type Target = T; + + fn deref(&self) -> &T { + unsafe { + let a = "imm_deref\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + *self + } +} + +impl Deref for &mut T { + type Target = T; + + fn deref(&self) -> &T { + unsafe { + let a = "mut_deref\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + *self + } +} + +struct Foo(T); +impl Deref for Foo { + type Target = T; + + fn deref(&self) -> &Self::Target { + unsafe { + let a = "foo_deref\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + &self.0 + } +} + +struct Bar(i32); +impl Bar { + fn cake(self) -> i32 { + self.0 + 1 + } +} + +pub fn main() { + let foo: Foo = Foo(Bar(123)); + let bar: Bar = *foo; + + let cake_result: i32 = foo.cake(); +} diff --git a/gcc/testsuite/rust/compile/torture/issue-893-2.rs b/gcc/testsuite/rust/compile/torture/issue-893-2.rs new file mode 100644 index 00000000000..88a865d66dc --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/issue-893-2.rs @@ -0,0 +1,35 @@ +// { dg-additional-options "-w" } +struct Foo(T); +impl Foo { + fn new(a: T, b: Y) -> Self { + Self(a) + } +} + +struct Bar(T); +impl Bar { + fn baz(self) {} + + fn test() -> i32 { + 123 + } +} + +struct Baz(A, B); +impl Baz { + fn test(a: X) -> X { + a + } +} + +pub fn main() { + let a = Foo::::new::(123, 456f32); + let b = Foo::new::(123, 456f32); + + let c = Bar::(123); + let d = Bar::baz(c); + + let e = Bar::test(); + + let f = Baz::test::(true); +} diff --git a/gcc/testsuite/rust/compile/torture/issue-893.rs b/gcc/testsuite/rust/compile/torture/issue-893.rs new file mode 100644 index 00000000000..d8245f3e0d8 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/issue-893.rs @@ -0,0 +1,11 @@ +// { dg-additional-options "-w" } +struct Foo(T); +impl Foo { + fn new(a: T, b: Y) -> Self { + Self(a) + } +} + +pub fn test() { + let a = Foo::::new::(123, 456f32); +} diff --git a/gcc/testsuite/rust/compile/torture/lazybooleanexpr_function.rs b/gcc/testsuite/rust/compile/torture/lazybooleanexpr_function.rs new file mode 100644 index 00000000000..1be51274d03 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/lazybooleanexpr_function.rs @@ -0,0 +1,14 @@ +fn foo() -> bool { + return true; +} + +fn bar() -> bool { + return false; +} + + + +fn main() { + let _a = true && foo(); + let _b = true || bar(); +} \ No newline at end of file diff --git a/gcc/testsuite/rust/compile/torture/lifetime1.rs b/gcc/testsuite/rust/compile/torture/lifetime1.rs new file mode 100644 index 00000000000..151fd827b5e --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/lifetime1.rs @@ -0,0 +1,7 @@ +fn foo<'a>(t: &'a str) -> &'a str { + t +} + +fn main() { + foo("hello world"); +} diff --git a/gcc/testsuite/rust/compile/torture/literals1.rs b/gcc/testsuite/rust/compile/torture/literals1.rs new file mode 100644 index 00000000000..cf021e295d2 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/literals1.rs @@ -0,0 +1,11 @@ +// { dg-prune-output "warning: unused name" } as there are many of these expected. + +fn main() { + let hex: i32 = 0xFF; + let binary: i32 = 0b11110000; + let oct: i32 = 0o70; + + let hex_u8: u8 = 0xFF_u8; + let bin_u16: u16 = 0b1111000011110000_u16; + let oct: u32 = 0o70_u32; +} diff --git a/gcc/testsuite/rust/compile/torture/loop1.rs b/gcc/testsuite/rust/compile/torture/loop1.rs new file mode 100644 index 00000000000..a8ee2f59bb8 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/loop1.rs @@ -0,0 +1,10 @@ +fn main() { + let mut a = 1; + let mut b = 1; + + loop { + let c = a + b; + a = b; + b = c; + } +} diff --git a/gcc/testsuite/rust/compile/torture/loop2.rs b/gcc/testsuite/rust/compile/torture/loop2.rs new file mode 100644 index 00000000000..3de3ea81947 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/loop2.rs @@ -0,0 +1,14 @@ +fn main() { + let mut a = 1; + let mut b = 1; + + // first number in Fibonacci sequence over 10: + loop { + if b > 10 { + break; + } + let c = a + b; + a = b; + b = c; + } +} diff --git a/gcc/testsuite/rust/compile/torture/loop3.rs b/gcc/testsuite/rust/compile/torture/loop3.rs new file mode 100644 index 00000000000..76fadfb4337 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/loop3.rs @@ -0,0 +1,14 @@ +fn main() { + let mut a = 1; + let mut b = 1; + + // first number in Fibonacci sequence over 10: + loop { + if b > 10 { + return; + } + let c = a + b; + a = b; + b = c; + } +} diff --git a/gcc/testsuite/rust/compile/torture/loop4.rs b/gcc/testsuite/rust/compile/torture/loop4.rs new file mode 100644 index 00000000000..f7b59357aeb --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/loop4.rs @@ -0,0 +1,7 @@ +fn main() { + 'outer: loop { + 'inner: loop { + break 'outer; + } + } +} diff --git a/gcc/testsuite/rust/compile/torture/loop5.rs b/gcc/testsuite/rust/compile/torture/loop5.rs new file mode 100644 index 00000000000..4004cd30b7b --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/loop5.rs @@ -0,0 +1,14 @@ +fn main() { + let mut a = 1; + let mut b = 1; + + // first number in Fibonacci sequence over 10: + let _fib = loop { + if b > 10 { + break b; + } + let c = a + b; + a = b; + b = c; + }; +} diff --git a/gcc/testsuite/rust/compile/torture/loop6.rs b/gcc/testsuite/rust/compile/torture/loop6.rs new file mode 100644 index 00000000000..ecd3ad4fd81 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/loop6.rs @@ -0,0 +1,11 @@ +fn main() { + let mut a = 1; + let mut b = 1; + + let mut c; + while b > 10 { + c = a + b; + a = b; + b = c; + } +} diff --git a/gcc/testsuite/rust/compile/torture/loop7.rs b/gcc/testsuite/rust/compile/torture/loop7.rs new file mode 100644 index 00000000000..0cd844592b6 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/loop7.rs @@ -0,0 +1,13 @@ +fn main() { + let mut a = 1; + let mut b = 1; + + let _fib = loop { + if (a % 2 == 0) { + continue; + } + let c = a + b; + a = b; + b = c; + }; +} diff --git a/gcc/testsuite/rust/compile/torture/macro-issue1403.rs b/gcc/testsuite/rust/compile/torture/macro-issue1403.rs new file mode 100644 index 00000000000..7fe6c51053c --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/macro-issue1403.rs @@ -0,0 +1,23 @@ +macro_rules! stmt { + ($s:stmt) => { + $s + }; + ($s:stmt, $($ss:stmt),*) => { + $s; + stmt!($($ss),*); + }; +} + +fn main() { + stmt!( + struct S; + ); + stmt!( + struct A;, + struct B;, + struct C;, + struct D;, + struct E; + ); +} + diff --git a/gcc/testsuite/rust/compile/torture/macro-issue1426.rs b/gcc/testsuite/rust/compile/torture/macro-issue1426.rs new file mode 100644 index 00000000000..1b558cfa83d --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/macro-issue1426.rs @@ -0,0 +1,32 @@ +// { dg-additional-options -fdump-tree-ccp1-raw } + +macro_rules! stmt { + ($s:stmt) => { + $s + }; + ($s:stmt, $($ss:stmt),*) => { + $s; + stmt!($($ss),*); + }; +} + +pub fn test() -> i32 { + stmt!( + let a = 1 + // { dg-warning {unused name 'a'} {} { target *-*-* } .-1 } + ); + stmt!( + let b = 2, + let c = 3, + let d = 4, + let e = 5, + let f = b + c + d + e + ); + f + // { dg-final { scan-tree-dump-times {gimple_return <14>} 1 ccp1 { target __OPTIMIZE__ } } } +} + +fn main() { + let _ = test(); +} + diff --git a/gcc/testsuite/rust/compile/torture/macro_as_expr.rs b/gcc/testsuite/rust/compile/torture/macro_as_expr.rs new file mode 100644 index 00000000000..b0084e7b466 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/macro_as_expr.rs @@ -0,0 +1,14 @@ +// { dg-additional-options "-w" } + +macro_rules! add { + ($a:expr) => { $a }; + ($a:expr, $($b:expr),+) => { $a + add!($($b),*) } +} + +fn main() -> i32 { + if add!(add!(1, 2)) > add!(5) { + add!(1, add!(2, 3), add!(4)) + } else { + add!(5, add!(6, 7), add!(8), 9) + 10 + } +} diff --git a/gcc/testsuite/rust/compile/torture/match1.rs b/gcc/testsuite/rust/compile/torture/match1.rs new file mode 100644 index 00000000000..916b11a3194 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/match1.rs @@ -0,0 +1,16 @@ +// { dg-additional-options "-w" } +enum Foo { + A, + B, + C(char), + D { x: i64, y: i64 }, +} + +fn inspect(f: Foo) { + match f { + Foo::A => {} + Foo::B => {} + Foo::C(x) => {} + Foo::D { x, y } => {} + } +} diff --git a/gcc/testsuite/rust/compile/torture/methods1.rs b/gcc/testsuite/rust/compile/torture/methods1.rs new file mode 100644 index 00000000000..a8e384dabea --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/methods1.rs @@ -0,0 +1,41 @@ +struct Point { + x: f64, + y: f64, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } +} + +impl Point { + fn origin() -> Point { + Point { x: 0.0, y: 0.0 } + } + + fn new(x: f64, y: f64) -> Point { + Point { x: x, y: y } + } +} + +struct Rectangle { + p1: Point, + p2: Point, +} + +impl Rectangle { + fn from(p1: Point, p2: Point) -> Self { + Self { p1, p2 } + } + + fn sum_x(self) -> f64 { + let p1 = self.p1; + let p2 = self.p2; + p1.x + p2.x + } +} + +fn main() { + let p1 = Point::origin(); + let p2 = Point::new(3.0, 4.0); + let rect = Rectangle::from(p1, p2); + + let sum = rect.sum_x(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/methods2.rs b/gcc/testsuite/rust/compile/torture/methods2.rs new file mode 100644 index 00000000000..d63211bdf8a --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/methods2.rs @@ -0,0 +1,43 @@ +struct Point { + x: f64, + y: f64, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } +} + +impl Point { + fn origin() -> Point { + Point { x: 0.0, y: 0.0 } + } + + fn new(x: f64, y: f64) -> Point { + Point { x: x, y: y } + } +} + +struct Rectangle { + p1: Point, + p2: Point, +} + +impl Rectangle { + fn from(p1: Point, p2: Point) -> Self { + Self { p1, p2 } + } +} + +fn main() { + let p1 = Point::origin(); + let p2 = Point::new(3.0, 4.0); + let rect = Rectangle::from(p1, p2); + + let sum = rect.sum_x(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} + +impl Rectangle { + fn sum_x(self) -> f64 { + let p1 = self.p1; + let p2 = self.p2; + p1.x + p2.x + } +} diff --git a/gcc/testsuite/rust/compile/torture/methods3.rs b/gcc/testsuite/rust/compile/torture/methods3.rs new file mode 100644 index 00000000000..55426f4fcf7 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/methods3.rs @@ -0,0 +1,44 @@ +struct Point { + x: f64, + y: f64, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } +} + +impl Point { + fn origin() -> Point { + Point { x: 0.0, y: 0.0 } + } + + fn new(x: f64, y: f64) -> Point { + Point { x: x, y: y } + } +} + +struct Rectangle { + p1: Point, + p2: Point, +} + +impl Rectangle { + fn from(p1: Point, p2: Point) -> Self { + Self { p1, p2 } + } + + fn sum_x(self) -> f64 { + let p1 = self.p1; + let p2 = self.p2; + p1.x + p2.x + } +} + +fn main() { + let p1 = Point::origin(); + let p2 = Point::new(3.0, 4.0); + let rect = Rectangle::from(p1, p2); + + let sum = rect.sum_x(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + // multiple MethodCallExpr were causing issue #310 + let sum = rect.sum_x(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/mod-nameresolve.rs b/gcc/testsuite/rust/compile/torture/mod-nameresolve.rs new file mode 100644 index 00000000000..09a722681b0 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/mod-nameresolve.rs @@ -0,0 +1,5 @@ +mod foo { + struct A; // { dg-warning "struct is never constructed" } +} + +fn main() {} diff --git a/gcc/testsuite/rust/compile/torture/mod1.rs b/gcc/testsuite/rust/compile/torture/mod1.rs new file mode 100644 index 00000000000..651678c6a34 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/mod1.rs @@ -0,0 +1,11 @@ +// This is testing name resolution + +mod _foo { + struct _A; +} + +mod _bar { + mod _barbis { + struct _B; + } +} diff --git a/gcc/testsuite/rust/compile/torture/mod2.rs b/gcc/testsuite/rust/compile/torture/mod2.rs new file mode 100644 index 00000000000..04722a94bb1 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/mod2.rs @@ -0,0 +1,13 @@ +mod foomod { + pub struct Foo {} +} + +impl foomod::Foo { + pub fn new() -> Self { + foomod::Foo {} + } +} + +fn main() { + let _a = foomod::Foo::new(); +} diff --git a/gcc/testsuite/rust/compile/torture/mod3.rs b/gcc/testsuite/rust/compile/torture/mod3.rs new file mode 100644 index 00000000000..2ace8c064d8 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/mod3.rs @@ -0,0 +1,22 @@ +// { dg-additional-options "-w" } +mod A { + pub mod B { + pub mod C { + pub struct Foo { + pub f: i32, + } + impl Foo { + pub fn new() -> Self { + Foo { f: 23i32 } + } + } + } + } +} + +fn main() -> i32 { + let a = A::B::C::Foo::new(); + let b = A::B::C::Foo { f: -23i32 }; + + a.f - b.f +} diff --git a/gcc/testsuite/rust/compile/torture/modules/mod.rs b/gcc/testsuite/rust/compile/torture/modules/mod.rs new file mode 100644 index 00000000000..3d65176b6c3 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/modules/mod.rs @@ -0,0 +1,3 @@ +pub fn return_12() -> i32 { + 12 +} diff --git a/gcc/testsuite/rust/compile/torture/modules/valid_path.rs b/gcc/testsuite/rust/compile/torture/modules/valid_path.rs new file mode 100644 index 00000000000..6a1519c3fc4 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/modules/valid_path.rs @@ -0,0 +1 @@ +fn unused() {} diff --git a/gcc/testsuite/rust/compile/torture/must_use1.rs b/gcc/testsuite/rust/compile/torture/must_use1.rs new file mode 100644 index 00000000000..95a6657c8c1 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/must_use1.rs @@ -0,0 +1,16 @@ +#[must_use = "TEST 1"] +fn test1() -> i32 { + 123 +} + +#[must_use = "TEST 2"] +fn test2() -> i32 { + 456 +} + +fn main() { + let _a = test1(); + + test2(); + // { dg-warning "ignoring return value of" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/must_use2.rs b/gcc/testsuite/rust/compile/torture/must_use2.rs new file mode 100644 index 00000000000..466f7ee7a14 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/must_use2.rs @@ -0,0 +1,16 @@ +trait A { + #[must_use] + fn test() -> i32; +} + +struct S; +impl A for S { + fn test() -> i32 { + 123 + } +} + +fn main() { + S::test(); + // { dg-warning "ignoring return value of" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/name_resolve1.rs b/gcc/testsuite/rust/compile/torture/name_resolve1.rs new file mode 100644 index 00000000000..817f48b60ee --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/name_resolve1.rs @@ -0,0 +1,23 @@ +struct Foo(i32, bool); + +impl Foo { + fn new(a: i32, b: bool) -> Foo { + Foo(a, b) + } + + fn test() -> i32 { + test() + } +} + +fn test() -> i32 { + 123 +} + +fn main() { + let a; + a = Foo::new(1, true); + + let b; + b = Foo::test(); +} diff --git a/gcc/testsuite/rust/compile/torture/negation_function.rs b/gcc/testsuite/rust/compile/torture/negation_function.rs new file mode 100644 index 00000000000..b592f9c00ef --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/negation_function.rs @@ -0,0 +1,7 @@ +fn ret1() -> i32 { + return 1; +} + +fn main() { + let _a = -ret1(); +} \ No newline at end of file diff --git a/gcc/testsuite/rust/compile/torture/nested_fn1.rs b/gcc/testsuite/rust/compile/torture/nested_fn1.rs new file mode 100644 index 00000000000..075b5dba8e0 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/nested_fn1.rs @@ -0,0 +1,10 @@ +pub fn main() { + let a = 123; + + fn test(x: i32) -> i32 { + x + 456 + } + + let b; + b = test(a); +} diff --git a/gcc/testsuite/rust/compile/torture/nested_fn2.rs b/gcc/testsuite/rust/compile/torture/nested_fn2.rs new file mode 100644 index 00000000000..7040c862e75 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/nested_fn2.rs @@ -0,0 +1,11 @@ +pub fn main() { + fn test(x: T) -> T { + x + } + + let mut a = 123; + a = test(a); + + let mut b = 456f32; + b = test(b); +} diff --git a/gcc/testsuite/rust/compile/torture/nested_struct1.rs b/gcc/testsuite/rust/compile/torture/nested_struct1.rs new file mode 100644 index 00000000000..2bd5eadd4c4 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/nested_struct1.rs @@ -0,0 +1,20 @@ +struct Point { + x: f64, + y: f64, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } +} + +struct Rectangle { + p1: Point, + p2: Point, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } +} + +fn main() { + let p1 = Point { x: 0.0, y: 0.0 }; + let p2 = Point { x: 2.0, y: 4.0 }; + let rect = Rectangle { p1, p2 }; + + let a = rect.p1.x; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/never_type1.rs b/gcc/testsuite/rust/compile/torture/never_type1.rs new file mode 100644 index 00000000000..0f15029097d --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/never_type1.rs @@ -0,0 +1,22 @@ +fn foo() -> i32 { + let c; + let d; + + c = if false { + return 1; + } else { + 0.0 + }; + + d = if true { + 0.0 + } else { + return 1; + }; + + 0 +} + +fn main() { + foo(); +} diff --git a/gcc/testsuite/rust/compile/torture/not_shebang.rs b/gcc/testsuite/rust/compile/torture/not_shebang.rs new file mode 100644 index 00000000000..37e01b65940 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/not_shebang.rs @@ -0,0 +1,3 @@ +#! +[allow(unused)] +fn main () { } diff --git a/gcc/testsuite/rust/compile/torture/not_shebang_block_comment.rs b/gcc/testsuite/rust/compile/torture/not_shebang_block_comment.rs new file mode 100644 index 00000000000..662f6506749 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/not_shebang_block_comment.rs @@ -0,0 +1 @@ +#!/*/this/is/a/comment*/[allow(unused)] fn main () { } diff --git a/gcc/testsuite/rust/compile/torture/not_shebang_comment.rs b/gcc/testsuite/rust/compile/torture/not_shebang_comment.rs new file mode 100644 index 00000000000..273ae4e8e2a --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/not_shebang_comment.rs @@ -0,0 +1,3 @@ +#!//this/is/a/comment +[allow(unused)] +fn main () { } diff --git a/gcc/testsuite/rust/compile/torture/not_shebang_multiline_comment.rs b/gcc/testsuite/rust/compile/torture/not_shebang_multiline_comment.rs new file mode 100644 index 00000000000..86800b14cb3 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/not_shebang_multiline_comment.rs @@ -0,0 +1,7 @@ +#!//this/is/a/comment + +/* Also a /* nested */ + multiline // comment + with some more whitespace after, but then finally a [, so not a real #! line. */ + +[allow(unused)] fn main () { } diff --git a/gcc/testsuite/rust/compile/torture/not_shebang_spaces.rs b/gcc/testsuite/rust/compile/torture/not_shebang_spaces.rs new file mode 100644 index 00000000000..6b94a69111a --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/not_shebang_spaces.rs @@ -0,0 +1,6 @@ +#! + + [allow(unused)] + + fn main () { } + diff --git a/gcc/testsuite/rust/compile/torture/parameter_usage1.rs b/gcc/testsuite/rust/compile/torture/parameter_usage1.rs new file mode 100644 index 00000000000..448e9603a94 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/parameter_usage1.rs @@ -0,0 +1,8 @@ +fn test(a: i32, b: i32) -> i32 { + a + b +} + +fn main() { + let a = test(1, 4); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/parens1.rs b/gcc/testsuite/rust/compile/torture/parens1.rs new file mode 100644 index 00000000000..795eb960805 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/parens1.rs @@ -0,0 +1,5 @@ +fn main() { + let a = 123; + let b = a + (a * 2); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/pointer1.rs b/gcc/testsuite/rust/compile/torture/pointer1.rs new file mode 100644 index 00000000000..f283411abe2 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/pointer1.rs @@ -0,0 +1,9 @@ +pub fn main() { + let mut num = 2; + let r1: *const i32 = # + let r2 = unsafe { *r1 } + unsafe { *r1 }; + let r3 = num; + num = 4; + let r4 = num + unsafe { *r1 } * r3; + let _eightteen = r2 + r3 + r4; +} diff --git a/gcc/testsuite/rust/compile/torture/primconsts.rs b/gcc/testsuite/rust/compile/torture/primconsts.rs new file mode 100644 index 00000000000..bcf9456d059 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/primconsts.rs @@ -0,0 +1,72 @@ +const TRUE: bool = true; +const FALSE: bool = !TRUE; + +const U8ZERO: u8 = 0; +const U8ONE: u8 = U8ZERO + 1; +const U16ZERO: u16 = 0; +const U16ONE: u16 = U16ZERO + 1; +const U32ZERO: u32 = 0; +const U32ONE: u32 = U32ZERO + 1; +const U64ZERO: u64 = 0; +const U64ONE: u64 = U64ZERO + 1; +const U128ZERO: u128 = 0; +const U128ONE: u128 = U128ZERO + 1; + +const I8ZERO: i8 = 0; +const I8ONE: i8 = I8ZERO + 1; +const I16ZERO: i16 = 0; +const I16ONE: i16 = I16ZERO + 1; +const I32ZERO: i32 = 0; +const I32ONE: i32 = I32ZERO + 1; +const I64ZERO: i64 = 0; +const I64ONE: i64 = I64ZERO + 1; +const I128ZERO: i128 = 0; +const I128ONE: i128 = I128ZERO + 1; + +const F32ZERO: f32 = 0.0; +const F32ONE: f32 = F32ZERO + 1.0; +const F64ZERO: f64 = 0.0; +const F64ONE: f64 = F64ZERO + 1.0; + +const USIZEZERO: usize = 0; +const USIZEONE: usize = USIZEZERO + 1; +const ISIZEZERO: isize = 0; +const ISIZEONE: isize = ISIZEZERO + 1; + +/* Not yet supported +const CHARPI: char = '\u{03C0}'; +const STRHELLO: &str = "Hello World!"; +*/ + +extern "C" { fn abort (); } + +pub fn main () +{ + if TRUE == FALSE { unsafe { abort (); } } + if U8ZERO > U8ONE { unsafe { abort (); } } + if U16ZERO > U16ONE { unsafe { abort (); } } + if U32ZERO > U32ONE { unsafe { abort (); } } + if U64ZERO > U64ONE { unsafe { abort (); } } + if U128ZERO > U128ONE { unsafe { abort (); } } + + if I8ONE <= I8ZERO { unsafe { abort (); } } + if I16ONE <= I16ZERO { unsafe { abort (); } } + if I32ONE <= I32ZERO { unsafe { abort (); } } + if I64ONE <= I64ZERO { unsafe { abort (); } } + if I128ONE <= I128ZERO { unsafe { abort (); } } + + if F32ZERO + F32ONE != F32ONE { unsafe { abort (); } } + if F64ZERO + F64ONE != F64ONE { unsafe { abort (); } } + + if USIZEZERO + USIZEONE - USIZEONE + USIZEZERO != USIZEZERO + { + unsafe { abort (); } + } + if ISIZEZERO + ISIZEONE - ISIZEONE + ISIZEZERO != ISIZEZERO + { + unsafe { abort (); } + } + + // if CHARPI != '\u{03c0}' { unsafe { abort (); } } + // if STRHELLO != "Hello World!" { unsafe { abort (); } } +} diff --git a/gcc/testsuite/rust/compile/torture/prims_struct_eq.rs b/gcc/testsuite/rust/compile/torture/prims_struct_eq.rs new file mode 100644 index 00000000000..81ab7424627 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/prims_struct_eq.rs @@ -0,0 +1,91 @@ +extern "C" +{ + fn abort (); +} + +struct Prims +{ + b1: bool, + b2: bool, + b3: bool, + b4: bool, + c1: char, + c2: char, + u81: u8, + u82: u8, + u83: u8, + u84: u8, + i81: i8, + i82: i8, + i83: i8, + i84: i8, + u161: u16, + u162: u16, + i161: i16, + i162: i16, + u321: u32, + u322: u32, + i321: i32, + i322: i32, + u641: u64, + i641: i64, + u1281: u128, + i1281: i128, + usize1: usize, + isize1: isize, +} + +fn prims_eq (p1: Prims, p2: Prims) -> bool +{ + return p1.b1 == p2.b1 + && p1.b2 == p2.b2 + && p1.b3 == p2.b3 + && p1.b4 == p2.b4 + && p1.c1 == p2.c1 + && p1.c2 == p2.c2 + && p1.u81 == p2.u81 + && p1.u82 == p2.u82 + && p1.u83 == p2.u83 + && p1.u84 == p2.u84 + && p1.i81 == p2.i81 + && p1.i82 == p2.i82 + && p1.i83 == p2.i83 + && p1.i84 == p2.i84 + && p1.u161 == p2.u161 + && p1.u162 == p2.u162 + && p1.i161 == p2.i161 + && p1.i162 == p2.i162 + && p1.u321 == p2.u321 + && p1.u322 == p2.u322 + && p1.i321 == p2.i321 + && p1.i322 == p2.i322 + && p1.u641 == p2.u641 + && p1.i641 == p2.i641 + && p1.u1281 == p2.u1281 + && p1.i1281 == p2.i1281 + && p1.usize1 == p2.usize1 + && p1.isize1 == p2.isize1; +} + +pub fn main () +{ + let p1 = Prims { b1: true, b2: false, b3: false, b4: true, + c1: 'a', c2: 'b', + u81: 1, u82: 2, u83: 3, u84: 4, + i81: -1, i82: -2, i83: -3, i84: -4, + u161: 1, u162: 2, + i161: -1, i162: -2, + u321: 1, u322: 2, + i321: -1, i322: -2, + u641: 1, + i641: -1, + u1281: 1, + i1281: -1, + usize1: 1, + isize1: -1 }; + let p2 = Prims { usize1: 1, .. p1 }; + let p3 = Prims { u1281: 0, .. p2 }; + let p4 = Prims { i1281: 0, .. p3 }; + if !prims_eq (p1, p2) { unsafe { abort (); } } + if prims_eq (p3, p4) { unsafe { abort (); } } +} diff --git a/gcc/testsuite/rust/compile/torture/range-lang-item1.rs b/gcc/testsuite/rust/compile/torture/range-lang-item1.rs new file mode 100644 index 00000000000..86946162276 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/range-lang-item1.rs @@ -0,0 +1,32 @@ +// { dg-additional-options "-w" } +#[lang = "RangeFull"] +pub struct RangeFull; + +#[lang = "Range"] +pub struct Range { + pub start: Idx, + pub end: Idx, +} + +#[lang = "RangeFrom"] +pub struct RangeFrom { + pub start: Idx, +} + +#[lang = "RangeTo"] +pub struct RangeTo { + pub end: Idx, +} + +#[lang = "RangeInclusive"] +pub struct RangeInclusive { + pub start: Idx, + pub end: Idx, +} + +fn test() { + let a = 1..2; // range + let b = 1..; // range from + let c = ..3; // range to + let d = 0..=2; // range inclusive +} diff --git a/gcc/testsuite/rust/compile/torture/raw_identifiers.rs b/gcc/testsuite/rust/compile/torture/raw_identifiers.rs new file mode 100644 index 00000000000..8746f337048 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/raw_identifiers.rs @@ -0,0 +1,3 @@ +pub fn square(num: i32) -> i32 { /* { dg-warning "used" } */ + r#num * num +} \ No newline at end of file diff --git a/gcc/testsuite/rust/compile/torture/raw_identifiers_keywords.rs b/gcc/testsuite/rust/compile/torture/raw_identifiers_keywords.rs new file mode 100644 index 00000000000..c9aa3cf4938 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/raw_identifiers_keywords.rs @@ -0,0 +1,3 @@ +pub fn plus(r#break: i32, r#unsafe: i32) -> i32 { /* { dg-warning "used" } */ + r#break + r#unsafe +} \ No newline at end of file diff --git a/gcc/testsuite/rust/compile/torture/recursive_fn1.rs b/gcc/testsuite/rust/compile/torture/recursive_fn1.rs new file mode 100644 index 00000000000..e13b41f70bd --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/recursive_fn1.rs @@ -0,0 +1,12 @@ +fn gcd(x: i32, y: i32) -> i32 { + if y == 0 { + x + } else { + gcd(y, x % y) + } +} + +fn main() { + let a = gcd(100, 5); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/return_function.rs b/gcc/testsuite/rust/compile/torture/return_function.rs new file mode 100644 index 00000000000..084adaf7f24 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/return_function.rs @@ -0,0 +1,5 @@ +fn foo() {} + +fn main() { + return foo(); +} diff --git a/gcc/testsuite/rust/compile/torture/scoping1.rs b/gcc/testsuite/rust/compile/torture/scoping1.rs new file mode 100644 index 00000000000..8bc8ede5f7c --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/scoping1.rs @@ -0,0 +1,11 @@ +fn main() { + let x = 1; + { + let mut x = true; + { + x = false; + } + } + let x = x + 1; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/self_type1.rs b/gcc/testsuite/rust/compile/torture/self_type1.rs new file mode 100644 index 00000000000..373d6dd5a60 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/self_type1.rs @@ -0,0 +1,12 @@ +struct Foo(i32, bool); + +impl Foo { + fn new(a: i32, b: bool) -> Self { + Self(a, b) + } +} + +fn main() { + let a; + a = Foo::new(1, true); +} diff --git a/gcc/testsuite/rust/compile/torture/shadow1.rs b/gcc/testsuite/rust/compile/torture/shadow1.rs new file mode 100644 index 00000000000..b60e7936de9 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/shadow1.rs @@ -0,0 +1,6 @@ +fn main() { + let mut x = 5; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let mut x; + x = true; +} diff --git a/gcc/testsuite/rust/compile/torture/shadow2.rs b/gcc/testsuite/rust/compile/torture/shadow2.rs new file mode 100644 index 00000000000..161dc380a07 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/shadow2.rs @@ -0,0 +1,5 @@ +fn main() { + let x = 1; + let x = x + 1; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/shebang.rs b/gcc/testsuite/rust/compile/torture/shebang.rs new file mode 100755 index 00000000000..1c8b9c9a955 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/shebang.rs @@ -0,0 +1,3 @@ +#!/usr/bin/env cat + +fn main () { } diff --git a/gcc/testsuite/rust/compile/torture/shebang_plus_attr.rs b/gcc/testsuite/rust/compile/torture/shebang_plus_attr.rs new file mode 100755 index 00000000000..075bc6cf594 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/shebang_plus_attr.rs @@ -0,0 +1,3 @@ +#!/usr/bin/env cat +#![allow(unused)] +fn main () { } diff --git a/gcc/testsuite/rust/compile/torture/shebang_plus_attr2.rs b/gcc/testsuite/rust/compile/torture/shebang_plus_attr2.rs new file mode 100755 index 00000000000..ece8a52381c --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/shebang_plus_attr2.rs @@ -0,0 +1,3 @@ +#!//usr/bin/env cat +#![allow(unused)] +fn main () { } diff --git a/gcc/testsuite/rust/compile/torture/static_function.rs b/gcc/testsuite/rust/compile/torture/static_function.rs new file mode 100644 index 00000000000..8e3a3795023 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/static_function.rs @@ -0,0 +1,8 @@ +fn test(x: i32) -> i32 { + return x + 1; +} + +fn main() { + let call_test = test(1); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/static_var1.rs b/gcc/testsuite/rust/compile/torture/static_var1.rs new file mode 100644 index 00000000000..5be0e75ce72 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/static_var1.rs @@ -0,0 +1,6 @@ +static x:i32 = 3; + +fn main() { + let y = x +1; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/stmt_with_block1.rs b/gcc/testsuite/rust/compile/torture/stmt_with_block1.rs new file mode 100644 index 00000000000..b6aa56cc2e6 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/stmt_with_block1.rs @@ -0,0 +1,13 @@ +fn test(x: i32) -> i32 { + if x > 1 { 1 } else { 2 }; + if x > 1 { 1; } else { 2; } + + { 3; } + { 3 }; + + { 3 } +} + +fn main() { + let a = test(0); // { dg-warning "unused name" } +} diff --git a/gcc/testsuite/rust/compile/torture/str1.rs b/gcc/testsuite/rust/compile/torture/str1.rs new file mode 100644 index 00000000000..088827853d8 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/str1.rs @@ -0,0 +1,7 @@ +fn main() { + let a; + a = "hello world infer"; + + let b: &str; + b = "hello world specified"; +} diff --git a/gcc/testsuite/rust/compile/torture/struct_access1.rs b/gcc/testsuite/rust/compile/torture/struct_access1.rs new file mode 100644 index 00000000000..ec85d289fb5 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/struct_access1.rs @@ -0,0 +1,12 @@ +struct Foo { + one: i32, + two: i32, +} + +fn main() { + let struct_test = Foo { one: 1, two: 2 }; + let a = struct_test.one; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let b = struct_test.two; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/struct_base_init_1.rs b/gcc/testsuite/rust/compile/torture/struct_base_init_1.rs new file mode 100644 index 00000000000..ee00c2c468b --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/struct_base_init_1.rs @@ -0,0 +1,13 @@ +struct Foo { + a: i32, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } + b: i32, +} + +fn foo() -> Foo { + Foo { a: 42, b: 32 } +} + +fn main() { + let _f = Foo { a: 10, ..foo() }; +} diff --git a/gcc/testsuite/rust/compile/torture/struct_decl.rs b/gcc/testsuite/rust/compile/torture/struct_decl.rs new file mode 100644 index 00000000000..9e8ea6b100b --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/struct_decl.rs @@ -0,0 +1,14 @@ +// { dg-additional-options "-fdump-tree-gimple -frust-crate=example" } + +struct Foo { + a: u16, + // { dg-warning "field is never read" "" { target *-*-* } .-1 } + b: u8, + // { dg-warning "field is never read" "" { target *-*-* } .-1 } +} + +fn main() { + let my_foo = Foo { a: 1, b: 2 }; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + // { dg-final { scan-tree-dump-times {(?n)const struct example::Foo my_foo;$} 1 gimple } } +} diff --git a/gcc/testsuite/rust/compile/torture/struct_init.rs b/gcc/testsuite/rust/compile/torture/struct_init.rs new file mode 100644 index 00000000000..1926f73b21d --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/struct_init.rs @@ -0,0 +1,11 @@ +struct Foo { + one: i32, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } + two: i32, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } +} + +fn main() { + let struct_test = Foo { one: 1, two: 2 }; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/struct_init_10.rs b/gcc/testsuite/rust/compile/torture/struct_init_10.rs new file mode 100644 index 00000000000..7fbceb03974 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/struct_init_10.rs @@ -0,0 +1,9 @@ +fn main() { + struct foo { + a: i32, + b: f32, + }; + + let a; + a = foo { a: 123, b: 456f32 }; +} diff --git a/gcc/testsuite/rust/compile/torture/struct_init_11.rs b/gcc/testsuite/rust/compile/torture/struct_init_11.rs new file mode 100644 index 00000000000..16a2f072566 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/struct_init_11.rs @@ -0,0 +1,34 @@ +pub fn main() { + struct O(i32); + struct T(i32, i32); + struct M(i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32); + + // tuples + let z = (); + let o = (0,); + let f = o.0; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let t = (0, 1); + let s = t.1; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let m = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + let l = m.10; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + // tuple structs + let so = O(0); + let sf = so.0; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let st = T(0, 1); + let fs = st.1; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let sm = M(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + let sl = sm.10; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + z +} diff --git a/gcc/testsuite/rust/compile/torture/struct_init_2.rs b/gcc/testsuite/rust/compile/torture/struct_init_2.rs new file mode 100644 index 00000000000..d7040d3d96d --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/struct_init_2.rs @@ -0,0 +1,6 @@ +struct Foo(f32, f32); + +fn main() { + let a = Foo { 0: 10.0, 1: 20.0 }; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/struct_init_3.rs b/gcc/testsuite/rust/compile/torture/struct_init_3.rs new file mode 100644 index 00000000000..1398f8e7b86 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/struct_init_3.rs @@ -0,0 +1,13 @@ +struct Foo { + a: i32, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } + b: i32, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } +} + +fn main() { + let a = 1; + let b = 2; + let c = Foo { a, b }; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/struct_init_4.rs b/gcc/testsuite/rust/compile/torture/struct_init_4.rs new file mode 100644 index 00000000000..2b2746aba7a --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/struct_init_4.rs @@ -0,0 +1,13 @@ +struct Foo { + a: i32, + // { dg-warning "field is never read" "" { target *-*-* } .-1 } + b: i32, + // { dg-warning "field is never read" "" { target *-*-* } .-1 } +} + +fn main() { + let a = Foo { a: 1, b: 2 }; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let b = Foo { a: 3, b: 4, ..a }; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/struct_init_5.rs b/gcc/testsuite/rust/compile/torture/struct_init_5.rs new file mode 100644 index 00000000000..891f64540fe --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/struct_init_5.rs @@ -0,0 +1,10 @@ +struct Foo { + a: i32, + b: i32, +} + +fn main() { + let a = Foo { a: 1, b: 2 }; + let b = Foo { ..a }; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/struct_init_6.rs b/gcc/testsuite/rust/compile/torture/struct_init_6.rs new file mode 100644 index 00000000000..9fc52ed5c50 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/struct_init_6.rs @@ -0,0 +1,11 @@ +struct Foo { + a: i32, + // { dg-warning "field is never read" "" { target *-*-* } .-1 } + b: i32, +} + +fn main() { + let a = Foo { a: 1, b: 2 }; + let b = Foo { a: 1, ..a }; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/struct_init_7.rs b/gcc/testsuite/rust/compile/torture/struct_init_7.rs new file mode 100644 index 00000000000..36dc00aca60 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/struct_init_7.rs @@ -0,0 +1,11 @@ +struct Foo { + a: i32, + b: f32, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } +} + +fn main() { + let c = Foo { a: 1, b: 2f32 }; + let b = Foo { b: 4f32, ..c }; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/struct_init_8.rs b/gcc/testsuite/rust/compile/torture/struct_init_8.rs new file mode 100644 index 00000000000..411ff7d1c6f --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/struct_init_8.rs @@ -0,0 +1,7 @@ +struct Foo(f32, i32); + +fn main() { + let a = Foo { 1: 1, 0: 2f32 }; + let b = Foo { ..a }; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/struct_init_9.rs b/gcc/testsuite/rust/compile/torture/struct_init_9.rs new file mode 100644 index 00000000000..2daa078d5b3 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/struct_init_9.rs @@ -0,0 +1,6 @@ +fn main() { + struct foo(i32, f32); + + let a; + a = foo(123, 456f32); +} diff --git a/gcc/testsuite/rust/compile/torture/top_attr.rs b/gcc/testsuite/rust/compile/torture/top_attr.rs new file mode 100644 index 00000000000..0671369cb12 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/top_attr.rs @@ -0,0 +1,5 @@ +#![crate_name = "name"] + + +#[allow(dead_code)] +fn main() {} \ No newline at end of file diff --git a/gcc/testsuite/rust/compile/torture/traits1.rs b/gcc/testsuite/rust/compile/torture/traits1.rs new file mode 100644 index 00000000000..90357738a81 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/traits1.rs @@ -0,0 +1,16 @@ +trait Foo { + fn bar() -> i32; +} + +struct Test(i32, f32); + +impl Foo for Test { + fn bar() -> i32 { + 123 + } +} + +fn main() { + let a: i32; + a = Test::bar(); +} diff --git a/gcc/testsuite/rust/compile/torture/traits10.rs b/gcc/testsuite/rust/compile/torture/traits10.rs new file mode 100644 index 00000000000..a02927007b3 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/traits10.rs @@ -0,0 +1,30 @@ +trait Foo // where +// Self: Sized, +{ + fn get(self) -> i32; + + fn test(self) -> i32 { + self.get() + } +} + +struct Bar(i32); +impl Foo for Bar { + fn get(self) -> i32 { + self.0 + } +} + +fn main() { + let a; + a = Bar(123); + + let b; + b = Bar::get(a); + + let a; + a = Bar(123); + + let b; + b = a.test(); +} diff --git a/gcc/testsuite/rust/compile/torture/traits11.rs b/gcc/testsuite/rust/compile/torture/traits11.rs new file mode 100644 index 00000000000..41c82f01b6d --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/traits11.rs @@ -0,0 +1,31 @@ +trait Foo { + type A; + + fn test(a: Self::A) -> Self::A { + a + } +} + +struct Bar(i32); +impl Foo for Bar { + type A = i32; +} + +struct Baz(f32); +impl Foo for Baz { + type A = f32; +} + +fn main() { + let a; + a = Bar(123); + + let b; + b = Bar::test(a.0); + + let c; + c = Baz(123f32); + + let d; + d = Baz::test(c.0); +} diff --git a/gcc/testsuite/rust/compile/torture/traits12.rs b/gcc/testsuite/rust/compile/torture/traits12.rs new file mode 100644 index 00000000000..a55b965baf0 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/traits12.rs @@ -0,0 +1,29 @@ +trait Foo { + type A; + + fn test(a: Self::A) -> Self::A { + a + } +} + +struct Bar(i32); +// { dg-warning "struct is never constructed" "" { target *-*-* } .-1 } + +impl Foo for Bar { + type A = i32; +} + +struct Baz(f32); +// { dg-warning "struct is never constructed" "" { target *-*-* } .-1 } + +impl Foo for Baz { + type A = f32; +} + +fn main() { + let a: ::A; + a = 123f32; + + let b; + b = ::test(a); +} diff --git a/gcc/testsuite/rust/compile/torture/traits13.rs b/gcc/testsuite/rust/compile/torture/traits13.rs new file mode 100644 index 00000000000..326f0390756 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/traits13.rs @@ -0,0 +1,17 @@ +trait Trait { + const FOO: usize; + type Target; +} + +struct S; +// { dg-warning "struct is never constructed" "" { target *-*-* } .-1 } + +impl Trait for S { + const FOO: usize = 0; + type Target = usize; +} + +fn main() { + let a: ::Target; + a = ::FOO; +} diff --git a/gcc/testsuite/rust/compile/torture/traits14.rs b/gcc/testsuite/rust/compile/torture/traits14.rs new file mode 100644 index 00000000000..8bca0d5c1f6 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/traits14.rs @@ -0,0 +1,23 @@ +trait Foo { + type A; + + fn test(a: T) -> T { + a + } +} + +struct Bar(T); +impl Foo for Bar { + type A = T; +} + +pub fn main() { + let a; + a = Bar(123); + + let b: as Foo>::A; + b = 456; + + let c: as Foo>::A; + c = as Foo>::test(a.0); +} diff --git a/gcc/testsuite/rust/compile/torture/traits15.rs b/gcc/testsuite/rust/compile/torture/traits15.rs new file mode 100644 index 00000000000..c8c40b78b45 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/traits15.rs @@ -0,0 +1,23 @@ +trait Foo { + type A; + + fn test(a: T, b: Self::A) -> (T, Self::A) { + (a, b) + } +} + +struct Bar(T); +impl Foo for Bar { + type A = T; +} + +pub fn main() { + let a; + a = Bar(123); + + let b: as Foo>::A; + b = 456; + + let c; + c = as Foo>::test(a.0, 123); +} diff --git a/gcc/testsuite/rust/compile/torture/traits16.rs b/gcc/testsuite/rust/compile/torture/traits16.rs new file mode 100644 index 00000000000..afc4a86de6d --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/traits16.rs @@ -0,0 +1,20 @@ +trait A { + fn a() -> i32 { + 123 + } + + fn b() -> i32 { + Self::a() + 456 + } +} + +struct S; +impl A for S {} + +fn main() { + let a; + a = S::a(); + + let b; + b = S::b(); +} diff --git a/gcc/testsuite/rust/compile/torture/traits17.rs b/gcc/testsuite/rust/compile/torture/traits17.rs new file mode 100644 index 00000000000..6da8bcb0082 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/traits17.rs @@ -0,0 +1,23 @@ +trait A { + fn a() -> i32 { + 123 + } +} + +trait B: A { + fn b() -> i32 { + Self::a() + 456 + } +} + +struct S; +impl A for S {} +impl B for S {} + +fn main() { + let a; + a = S::a(); + + let b; + b = S::b(); +} diff --git a/gcc/testsuite/rust/compile/torture/traits18.rs b/gcc/testsuite/rust/compile/torture/traits18.rs new file mode 100644 index 00000000000..63319dd2daa --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/traits18.rs @@ -0,0 +1,5 @@ +trait Foo<'a> {} + +trait Bar { + type Item: for<'a> Foo<'a>; +} diff --git a/gcc/testsuite/rust/compile/torture/traits19.rs b/gcc/testsuite/rust/compile/torture/traits19.rs new file mode 100644 index 00000000000..4412656f535 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/traits19.rs @@ -0,0 +1,33 @@ +// { dg-additional-options "-w" } +trait Get { + type Value; + fn get(&self) -> &::Value; +} + +struct Struct { + x: isize, +} + +impl Get for Struct { + type Value = isize; + fn get(&self) -> &isize { + &self.x + } +} + +trait Grab { + type U; + fn grab(&self) -> &::U; +} + +impl Grab for T { + type U = ::Value; + fn grab(&self) -> &::Value { + self.get() + } +} + +fn main() { + let s = Struct { x: 100 }; + let a = s.grab(); +} diff --git a/gcc/testsuite/rust/compile/torture/traits2.rs b/gcc/testsuite/rust/compile/torture/traits2.rs new file mode 100644 index 00000000000..fc6eb6002e0 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/traits2.rs @@ -0,0 +1,16 @@ +trait Foo { + fn bar() -> i32; +} + +struct Test(T); + +impl Foo for Test { + fn bar() -> i32 { + 123 + } +} + +fn main() { + let a: i32; + a = Test::::bar(); +} diff --git a/gcc/testsuite/rust/compile/torture/traits3.rs b/gcc/testsuite/rust/compile/torture/traits3.rs new file mode 100644 index 00000000000..deeb81e0946 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/traits3.rs @@ -0,0 +1,15 @@ +pub trait Foo { + fn Bar(self) -> i32; +} + +struct Baz; +// { dg-warning "struct is never constructed: .Baz." "" { target *-*-* } .-1 } + +impl Foo for Baz { + fn Bar(self) -> i32 { + // { dg-warning "unused name .self." "" { target *-*-* } .-1 } + 123 + } +} + +fn main() {} diff --git a/gcc/testsuite/rust/compile/torture/traits4.rs b/gcc/testsuite/rust/compile/torture/traits4.rs new file mode 100644 index 00000000000..67b012c11f5 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/traits4.rs @@ -0,0 +1,21 @@ +trait Foo { + type A; + type B; + + fn new(a: Self::A, b: Self::B) -> Self; +} + +struct Baz(i32, f32); + +impl Foo for Baz { + type A = i32; + type B = f32; + + fn new(a: Self::A, b: Self::B) -> Self { + Baz(a, b) + } +} + +fn main() { + Baz::new(123, 456f32); +} diff --git a/gcc/testsuite/rust/compile/torture/traits5.rs b/gcc/testsuite/rust/compile/torture/traits5.rs new file mode 100644 index 00000000000..445b0658f5c --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/traits5.rs @@ -0,0 +1,21 @@ +trait Foo { + type A; + type B; + + fn new(a: Self::A, b: Self::B) -> Self; +} + +struct Baz(i32, f32); + +impl Foo for Baz { + type A = i32; + type B = f32; + + fn new(a: i32, b: f32) -> Self { + Baz(a, b) + } +} + +fn main() { + Baz::new(123, 456f32); +} diff --git a/gcc/testsuite/rust/compile/torture/traits6.rs b/gcc/testsuite/rust/compile/torture/traits6.rs new file mode 100644 index 00000000000..260dde3f465 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/traits6.rs @@ -0,0 +1,20 @@ +trait Foo { + type A; + + fn baz(a: Self::A) -> Self::A; +} + +struct Bar(T); + +impl Foo for Bar { + type A = T; + + fn baz(a: Self::A) -> T { + a + } +} + +fn main() { + let a; + a = Bar::::baz(123); +} diff --git a/gcc/testsuite/rust/compile/torture/traits7.rs b/gcc/testsuite/rust/compile/torture/traits7.rs new file mode 100644 index 00000000000..7bc3384ab41 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/traits7.rs @@ -0,0 +1,19 @@ +trait Foo { + const A: i32; + + fn test(self); +} + +struct Bar; +impl Foo for Bar { + const A: i32 = 123; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + fn test(self) {} + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} + +fn main() { + let a = Bar; + a.test(); +} diff --git a/gcc/testsuite/rust/compile/torture/traits8.rs b/gcc/testsuite/rust/compile/torture/traits8.rs new file mode 100644 index 00000000000..459032fb4a2 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/traits8.rs @@ -0,0 +1,21 @@ +trait Foo { + fn default() -> i32; +} + +struct Bar(i32); +// { dg-warning "struct is never constructed" "" { target *-*-* } .-1 } + +impl Foo for Bar { + fn default() -> i32 { + 123 + } +} + +fn type_bound_test() -> i32 { + T::default() +} + +fn main() { + let a; + a = type_bound_test::(); +} diff --git a/gcc/testsuite/rust/compile/torture/traits9.rs b/gcc/testsuite/rust/compile/torture/traits9.rs new file mode 100644 index 00000000000..89e4bf19b0c --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/traits9.rs @@ -0,0 +1,27 @@ +trait Foo { + fn default() -> i32; + fn get(self) -> i32; +} + +struct Bar(i32); +impl Foo for Bar { + fn default() -> i32 { + 123 + } + + fn get(self) -> i32 { + self.0 + } +} + +fn type_bound_test(a: T) -> i32 { + T::default() + a.get() +} + +fn main() { + let a; + a = Bar(456); + + let b; + b = type_bound_test(a); +} diff --git a/gcc/testsuite/rust/compile/torture/transmute-size-check-1.rs b/gcc/testsuite/rust/compile/torture/transmute-size-check-1.rs new file mode 100644 index 00000000000..461a35de8ef --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/transmute-size-check-1.rs @@ -0,0 +1,11 @@ +mod mem { + extern "rust-intrinsic" { + fn size_of() -> usize; + fn transmute(_: U) -> V; // { dg-error "cannot transmute between types of different sizes, or dependently-sized types" } + } +} + +fn main() { + let a = 123; + let _b: [u32; mem::size_of::()] = unsafe { mem::transmute(a) }; +} diff --git a/gcc/testsuite/rust/compile/torture/transmute1.rs b/gcc/testsuite/rust/compile/torture/transmute1.rs new file mode 100644 index 00000000000..af9a55d1b97 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/transmute1.rs @@ -0,0 +1,11 @@ +mod mem { + extern "rust-intrinsic" { + fn size_of() -> usize; + fn transmute(_: U) -> V; + } +} + +fn main() { + let a = 123; + let _b: [u8; mem::size_of::()] = unsafe { mem::transmute(a) }; +} diff --git a/gcc/testsuite/rust/compile/torture/tuple1.rs b/gcc/testsuite/rust/compile/torture/tuple1.rs new file mode 100644 index 00000000000..9e6f613f682 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/tuple1.rs @@ -0,0 +1,6 @@ +fn main() { + let a: (i32, bool) = (123, true); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let b; + b = (456, 5f32); +} diff --git a/gcc/testsuite/rust/compile/torture/tuple2.rs b/gcc/testsuite/rust/compile/torture/tuple2.rs new file mode 100644 index 00000000000..ab3d0b8715b --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/tuple2.rs @@ -0,0 +1,5 @@ +fn main() { + let a = 123; + let b = (a,); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/tuple3.rs b/gcc/testsuite/rust/compile/torture/tuple3.rs new file mode 100644 index 00000000000..d0fb6fc4429 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/tuple3.rs @@ -0,0 +1,9 @@ +fn main() { + let a = (1, true); + + let b; + let c; + + b = a.0; + c = a.1; +} diff --git a/gcc/testsuite/rust/compile/torture/tuple_enum_variants.rs b/gcc/testsuite/rust/compile/torture/tuple_enum_variants.rs new file mode 100644 index 00000000000..d953e3d89a1 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/tuple_enum_variants.rs @@ -0,0 +1,23 @@ +enum E { + T0(), + T1(i32), + T2(i32, u32), +} + +/* The following doesn't parse yet... +fn f(e0: E, e1: E, e2: E) -> (E,E,E,()) +{ + let e = e0; + let f = e1; + let g = e2; + (e,f,g,()) +} + +fn main() +{ + let e0 = E::T0(); + let e1 = E::T1(0); + let e2 = E::T2(0,1); + f(e0, e1, e2).3 +} +*/ diff --git a/gcc/testsuite/rust/compile/torture/tuple_field_access.rs b/gcc/testsuite/rust/compile/torture/tuple_field_access.rs new file mode 100644 index 00000000000..8d1bbe9906c --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/tuple_field_access.rs @@ -0,0 +1,6 @@ +struct Foo(i32, i32); + +fn main() { + let mut a = Foo(1, 2); + a.0 = 22; +} diff --git a/gcc/testsuite/rust/compile/torture/tuple_function.rs b/gcc/testsuite/rust/compile/torture/tuple_function.rs new file mode 100644 index 00000000000..514b586cc09 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/tuple_function.rs @@ -0,0 +1,6 @@ +fn foo() -> i32 { + return 1; +} +fn main() { + let _a = (foo(), 2); +} diff --git a/gcc/testsuite/rust/compile/torture/tuple_index.rs b/gcc/testsuite/rust/compile/torture/tuple_index.rs new file mode 100644 index 00000000000..f904fae9b5b --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/tuple_index.rs @@ -0,0 +1,32 @@ +fn main() +{ + // tuples + let z = (); + + let o = (0,); + let _f = o.0; + + let t = (0,1); + let _s = t.1; + + let m = (0,1,2,3,4,5,6,7,8,9,10); + let _l = m.10; + + // tuple structs + struct E(); + let _e = E(); + + struct O(i32); + let so = O(0); + let _sf = so.0; + + struct T(i32,i32); + let st = T(0,1); + let _fs = st.1; + + struct M(i32,i32,i32,i32,i32,i32,i32,i32,i32,i32,i32); + let sm = M(0,1,2,3,4,5,6,7,8,9,10); + let _sl = sm.10; + + z +} diff --git a/gcc/testsuite/rust/compile/torture/tuple_struct1.rs b/gcc/testsuite/rust/compile/torture/tuple_struct1.rs new file mode 100644 index 00000000000..0ac19b179a9 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/tuple_struct1.rs @@ -0,0 +1,6 @@ +struct Foo(i32, i32, bool); + +fn main() { + let a = Foo(1, 2, true); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/tuple_struct2.rs b/gcc/testsuite/rust/compile/torture/tuple_struct2.rs new file mode 100644 index 00000000000..5e0a76e1de8 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/tuple_struct2.rs @@ -0,0 +1,11 @@ +struct Foo(i32, bool); + +fn main() { + let a = Foo(1, true); + + let b; + let c; + + b = a.0; + c = a.1; +} diff --git a/gcc/testsuite/rust/compile/torture/tuple_struct_unit.rs b/gcc/testsuite/rust/compile/torture/tuple_struct_unit.rs new file mode 100644 index 00000000000..cda19d2af0b --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/tuple_struct_unit.rs @@ -0,0 +1,11 @@ +struct E(); +struct T(E,E,()); + +fn main() +{ + let z0 = E(); + let z1 = E(); + let t = T(z0,z1,()); + let z = t.2; + z +} diff --git a/gcc/testsuite/rust/compile/torture/tuple_struct_unused.rs b/gcc/testsuite/rust/compile/torture/tuple_struct_unused.rs new file mode 100644 index 00000000000..8da0a50632b --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/tuple_struct_unused.rs @@ -0,0 +1,4 @@ +struct Foo(i32, i32); +// { dg-warning "struct is never constructed" "" { target *-*-* } .-1 } + +fn main() {} diff --git a/gcc/testsuite/rust/compile/torture/type-alias1.rs b/gcc/testsuite/rust/compile/torture/type-alias1.rs new file mode 100644 index 00000000000..78bf0461036 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/type-alias1.rs @@ -0,0 +1,6 @@ +type TypeAlias = (i32, u32); + +fn main() { + let a: TypeAlias; + a = (123, 456); +} diff --git a/gcc/testsuite/rust/compile/torture/type-alias2.rs b/gcc/testsuite/rust/compile/torture/type-alias2.rs new file mode 100644 index 00000000000..a3e3f4e6851 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/type-alias2.rs @@ -0,0 +1,8 @@ +type x = u32; + +fn main() { + let x: x = 1; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let y: x = 2; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/type_infer1.rs b/gcc/testsuite/rust/compile/torture/type_infer1.rs new file mode 100644 index 00000000000..3fee7282bde --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/type_infer1.rs @@ -0,0 +1,24 @@ +struct Foo { + one: i32, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } + two: i32, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } +} + +fn test(x: i32) -> i32 { + return x + 1; +} + +fn main() { + let logical: bool = true; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let an_integer = 5; + let mut default_integer = 7; + + default_integer = 1 + an_integer; + + let call_test = test(1); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let struct_test = Foo { one: 1, two: 2 }; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/type_infer2.rs b/gcc/testsuite/rust/compile/torture/type_infer2.rs new file mode 100644 index 00000000000..dcddda42729 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/type_infer2.rs @@ -0,0 +1,9 @@ +fn test(x: i32) -> i32 { + return x + 1; +} + +fn main() { + let an_integer = 5; + let call_test = test(an_integer + 1); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/type_infer3.rs b/gcc/testsuite/rust/compile/torture/type_infer3.rs new file mode 100644 index 00000000000..303dd3d1f18 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/type_infer3.rs @@ -0,0 +1,14 @@ +fn test(x: i32) -> i32 { + return x + 1; +} + +fn main() { + let mut an_integer = 5; + an_integer = test(1) + 3; + + let mut x; + x = 1; + + let call_test = test(1); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/type_infer4.rs b/gcc/testsuite/rust/compile/torture/type_infer4.rs new file mode 100644 index 00000000000..77a919f262a --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/type_infer4.rs @@ -0,0 +1,11 @@ +fn main() { + let xs: [i32; 5] = [1, 2, 3, 4, 5]; + let xy = [6, 7, 8]; + + let a = xs[0]; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let b = xy[2]; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let mut c; + c = xs[0]; +} diff --git a/gcc/testsuite/rust/compile/torture/type_infer5.rs b/gcc/testsuite/rust/compile/torture/type_infer5.rs new file mode 100644 index 00000000000..2c2602a161f --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/type_infer5.rs @@ -0,0 +1,13 @@ +struct Foo { + a: i32, + b: i32, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } +} + +fn main() { + let a; + a = Foo { a: 1, b: 2 }; + + let b = a.a; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/type_infer6.rs b/gcc/testsuite/rust/compile/torture/type_infer6.rs new file mode 100644 index 00000000000..6f5863f0107 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/type_infer6.rs @@ -0,0 +1,14 @@ +fn test(x: u32) -> u32 { + return x + 1; +} + +fn main() { + let a; + a = 1; + let b = test(a); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let c = 1; + let d = test(c + 1); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/unary_operators.rs b/gcc/testsuite/rust/compile/torture/unary_operators.rs new file mode 100644 index 00000000000..9be729c04e3 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/unary_operators.rs @@ -0,0 +1,8 @@ +// { dg-prune-output "warning: unused name" } as there are many of these expected. + +fn main() { + let a: i32 = -1; + let b: i32 = 3 - -1; + let c: bool = !false; + let d: i32 = !3; +} diff --git a/gcc/testsuite/rust/compile/torture/undended-string-1.rs b/gcc/testsuite/rust/compile/torture/undended-string-1.rs new file mode 100644 index 00000000000..66f0cd52269 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/undended-string-1.rs @@ -0,0 +1,5 @@ +// { dg-excess-errors "...." } +fn main() { + // { dg-error "unended string literal" "" { target *-*-* } .+1 } + let s = "123 +} diff --git a/gcc/testsuite/rust/compile/torture/undended-string-2.rs b/gcc/testsuite/rust/compile/torture/undended-string-2.rs new file mode 100644 index 00000000000..c0f424927c2 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/undended-string-2.rs @@ -0,0 +1,5 @@ +// { dg-excess-errors "...." } +fn main() { + // { dg-error "unended byte string literal" "" { target *-*-* } .+1 } + let s = b"123 +} diff --git a/gcc/testsuite/rust/compile/torture/underscore_id.rs b/gcc/testsuite/rust/compile/torture/underscore_id.rs new file mode 100644 index 00000000000..2c106c55df9 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/underscore_id.rs @@ -0,0 +1,4 @@ +fn main() { + let _unused_but_fine = 12; + let unused = 12; // { dg-warning "unused name" } +} diff --git a/gcc/testsuite/rust/compile/torture/union.rs b/gcc/testsuite/rust/compile/torture/union.rs new file mode 100644 index 00000000000..724168817ad --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/union.rs @@ -0,0 +1,32 @@ +union U +{ + f1: u8 +} + +union V +{ + f1: u8, + f2: u16, + f3: i32, +} + +struct S +{ + f1: U, + f2: V +} + +fn main () +{ + let u = U { f1: 16 }; + let v = V { f2: 365 }; + let s = S { f1: u, f2: v }; + let _v125 = unsafe + { let mut uv: u64; + uv = s.f1.f1 as u64; + uv += s.f2.f1 as u64; + uv += s.f2.f2 as u64; + uv -= s.f2.f3 as u64; + uv + }; +} diff --git a/gcc/testsuite/rust/compile/torture/union_union.rs b/gcc/testsuite/rust/compile/torture/union_union.rs new file mode 100644 index 00000000000..9feb145a692 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/union_union.rs @@ -0,0 +1,27 @@ +union union +{ + union: u32, + inion: i32, + u8ion: u8, + i64on: i64, + u64on: u64 +} + +pub fn main () +{ + let union = union { union: 2 }; + let inion = union { inion: -2 }; + let mut mnion = union { inion: -16 }; + let m1 = unsafe { mnion.union }; + unsafe { mnion.union = union.union }; + let m2 = unsafe { mnion.inion }; + let u1 = unsafe { union.union }; + let i1 = unsafe { union.inion }; + let u2 = unsafe { inion.union }; + let i2 = unsafe { inion.inion }; + let _r1 = u2 - u1 - m1; + let _r2 = i1 + i2 + m2; + let _u8 = unsafe { union.u8ion }; + let _i64 = unsafe { union.i64on }; + let _u64 = unsafe { union.u64on }; +} diff --git a/gcc/testsuite/rust/compile/torture/unit_type1.rs b/gcc/testsuite/rust/compile/torture/unit_type1.rs new file mode 100644 index 00000000000..d5f73575745 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/unit_type1.rs @@ -0,0 +1,7 @@ +fn main() { + let a: () = (); + // { dg-warning "unused name" "" { target *-*-* } .-1 } + + let b; + b = (); +} diff --git a/gcc/testsuite/rust/compile/torture/unit_type2.rs b/gcc/testsuite/rust/compile/torture/unit_type2.rs new file mode 100644 index 00000000000..b5f925907d8 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/unit_type2.rs @@ -0,0 +1,8 @@ +fn test(a: ()) -> () { + a +} + +fn main() { + let a; + a = test(()); +} diff --git a/gcc/testsuite/rust/compile/torture/unit_type3.rs b/gcc/testsuite/rust/compile/torture/unit_type3.rs new file mode 100644 index 00000000000..d48a691046b --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/unit_type3.rs @@ -0,0 +1,6 @@ +struct S; + +fn main() { + let s = S; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/unit_type4.rs b/gcc/testsuite/rust/compile/torture/unit_type4.rs new file mode 100644 index 00000000000..ccbfa21818a --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/unit_type4.rs @@ -0,0 +1,5 @@ +struct S; + +fn main() { + let _s = S {}; +} diff --git a/gcc/testsuite/rust/compile/torture/unit_type5.rs b/gcc/testsuite/rust/compile/torture/unit_type5.rs new file mode 100644 index 00000000000..3c4323aa73c --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/unit_type5.rs @@ -0,0 +1,8 @@ +struct Foo; + +fn main() { + let a = Foo {}; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let b = Foo; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/unsafe1.rs b/gcc/testsuite/rust/compile/torture/unsafe1.rs new file mode 100644 index 00000000000..f57ef52b9c0 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/unsafe1.rs @@ -0,0 +1,12 @@ +fn test() -> i32 { + unsafe { + let a; + a = 123; + a + } +} + +fn main() { + let a; + a = test(); +} diff --git a/gcc/testsuite/rust/compile/torture/unsafe2.rs b/gcc/testsuite/rust/compile/torture/unsafe2.rs new file mode 100644 index 00000000000..0b3aad53a44 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/unsafe2.rs @@ -0,0 +1,4 @@ +fn main() { + unsafe {} + () +} diff --git a/gcc/testsuite/rust/compile/torture/unsafe3.rs b/gcc/testsuite/rust/compile/torture/unsafe3.rs new file mode 100644 index 00000000000..5f427258f60 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/unsafe3.rs @@ -0,0 +1,9 @@ +pub fn test() -> i32 { + let a = unsafe { 123 }; + a +} + +pub fn main() { + let a = test(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/unsafe4.rs b/gcc/testsuite/rust/compile/torture/unsafe4.rs new file mode 100644 index 00000000000..6fe3101d49c --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/unsafe4.rs @@ -0,0 +1,12 @@ +struct SS { + one: i32, + two: i32, +} +struct TS(i32, i32); + +fn main() { + unsafe { + let ss = SS { one: 1, two: 2 }; + let _ts = TS(ss.one, ss.two); + }; +} diff --git a/gcc/testsuite/rust/compile/torture/unused.rs b/gcc/testsuite/rust/compile/torture/unused.rs new file mode 100644 index 00000000000..d95e6b01c00 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/unused.rs @@ -0,0 +1,17 @@ +// { dg-warning "function is never used: 'bar'" "" { target *-*-* } .+1 } +fn bar() { + foo(); +} + +// { dg-warning "function is never used: 'foo'" "" { target *-*-* } .+1 } +fn foo() { + bar(); +} + +fn f() { + +} + +fn main() { + f(); +} diff --git a/gcc/testsuite/rust/compile/torture/unused1.rs b/gcc/testsuite/rust/compile/torture/unused1.rs new file mode 100644 index 00000000000..db7eb8fc1fc --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/unused1.rs @@ -0,0 +1,15 @@ +fn test() -> i32 { + 1 +} + +fn unused() -> i32 { + // { dg-warning "function is never used: 'unused'" "" { target *-*-* } .-1 } + 2 +} + +fn main() { + let a = 1; + // { dg-warning "unused name" "" { target *-*-* } .-1 } + let b = test(); + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/unused_struct.rs b/gcc/testsuite/rust/compile/torture/unused_struct.rs new file mode 100644 index 00000000000..ba9ec3250cf --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/unused_struct.rs @@ -0,0 +1,7 @@ +struct Foo { + // { dg-warning "struct is never constructed" "" { target *-*-* } .-1 } + one: i32, + two: i32, +} + +fn main() {} diff --git a/gcc/testsuite/rust/compile/torture/unused_struct_field.rs b/gcc/testsuite/rust/compile/torture/unused_struct_field.rs new file mode 100644 index 00000000000..429b3039da4 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/unused_struct_field.rs @@ -0,0 +1,9 @@ +struct Foo { + one: i32, +// { dg-warning "field is never read" "" { target *-*-* } .-1 } + two: i32 +} +fn main() { + let _a = Foo {one: 1, two: 2}; + let _b = _a.two; +} \ No newline at end of file diff --git a/gcc/testsuite/rust/compile/torture/usize1.rs b/gcc/testsuite/rust/compile/torture/usize1.rs new file mode 100644 index 00000000000..ba1d5c60320 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/usize1.rs @@ -0,0 +1,6 @@ +fn main() { + let a = [1, 2, 3]; + let b: usize = 1; + let c = a[b]; + // { dg-warning "unused name" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/torture/very-broken-attr-string.rs b/gcc/testsuite/rust/compile/torture/very-broken-attr-string.rs new file mode 100644 index 00000000000..832ba7b8ec9 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/very-broken-attr-string.rs @@ -0,0 +1,3 @@ +// { dg-excess-errors "...." } +// { dg-error "unended string literal" "" { target *-*-* } .+1 } +#[doc(alias = "123 diff --git a/gcc/testsuite/rust/compile/torture/while_function.rs b/gcc/testsuite/rust/compile/torture/while_function.rs new file mode 100644 index 00000000000..014db902769 --- /dev/null +++ b/gcc/testsuite/rust/compile/torture/while_function.rs @@ -0,0 +1,10 @@ +fn foo() {} +fn bar() -> i32 { return 10; } + +fn main() { + let mut i = 1; + while i < bar() { + foo(); + i += 1; + } +} diff --git a/gcc/testsuite/rust/compile/traits1.rs b/gcc/testsuite/rust/compile/traits1.rs new file mode 100644 index 00000000000..355064eec1a --- /dev/null +++ b/gcc/testsuite/rust/compile/traits1.rs @@ -0,0 +1,13 @@ +trait Foo { + fn Bar() -> i32 {} + // { dg-error "expected .i32. got .()." "" { target *-*-* } .-1 } +} + +struct Baz; + +impl Foo for Baz { + fn Barrr() {} + // { dg-error "method .Barrr. is not a member of trait .Foo." "" { target *-*-* } .-1 } +} + +fn main() {} diff --git a/gcc/testsuite/rust/compile/traits10.rs b/gcc/testsuite/rust/compile/traits10.rs new file mode 100644 index 00000000000..f8f551ba86d --- /dev/null +++ b/gcc/testsuite/rust/compile/traits10.rs @@ -0,0 +1,15 @@ +struct Foo(i32); + +trait Bar { + const A: i32 = 123; + fn B(); + fn C(&self); +} + +pub fn main() { + let a; + a = Foo(123); + + let b: &dyn Bar = &a; + // { dg-error "trait bound is not object safe" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/traits11.rs b/gcc/testsuite/rust/compile/traits11.rs new file mode 100644 index 00000000000..d06e47d7e16 --- /dev/null +++ b/gcc/testsuite/rust/compile/traits11.rs @@ -0,0 +1,19 @@ +struct Foo(i32); + +trait A { + const A: i32 = 123; + fn B(); + fn C(&self); +} + +trait B: A { + fn test(&self); +} + +pub fn main() { + let a; + a = Foo(123); + + let b: &dyn B = &a; + // { dg-error "trait bound is not object safe" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/traits12.rs b/gcc/testsuite/rust/compile/traits12.rs new file mode 100644 index 00000000000..25e0eb7aaa3 --- /dev/null +++ b/gcc/testsuite/rust/compile/traits12.rs @@ -0,0 +1,20 @@ +trait A { + type Output; + + fn test(self, a: &T) -> &Self::Output; +} + +struct Foo { + start: T, + end: T, +} + +impl A for Foo { + // { dg-error "generic item takes at least 1 type arguments but 0 were supplied" "" { target *-*-* } .-1 } + // { dg-error "unconstrained type parameter" "" { target *-*-* } .-2 } + type Output = T; + + fn test(self, a: &T) -> &Self::Output { + a + } +} diff --git a/gcc/testsuite/rust/compile/traits2.rs b/gcc/testsuite/rust/compile/traits2.rs new file mode 100644 index 00000000000..7357c22f7d6 --- /dev/null +++ b/gcc/testsuite/rust/compile/traits2.rs @@ -0,0 +1,14 @@ +trait Foo { + fn Bar() -> i32 {} + // { dg-error "expected .i32. got .()." "" { target *-*-* } .-1 } +} + +struct Baz; + +impl Foo for Baz { + fn Bar() {} + // { dg-error "expected .i32. got .()." "" { target *-*-* } .-1 } + // { dg-error "method .Bar. has an incompatible type for trait .Foo." "" { target *-*-* } .-2 } +} + +fn main() {} diff --git a/gcc/testsuite/rust/compile/traits3.rs b/gcc/testsuite/rust/compile/traits3.rs new file mode 100644 index 00000000000..fd3fa457cc8 --- /dev/null +++ b/gcc/testsuite/rust/compile/traits3.rs @@ -0,0 +1,22 @@ +trait Foo { + type A; + + fn baz(a: Self::A) -> Self::A; +} + +struct Bar(T); + +impl Foo for Bar { + type A = i32; + + fn baz(a: f32) -> f32 { + // { dg-error "method .baz. has an incompatible type for trait .Foo." "" { target *-*-* } .-1 } + a + // { dg-error "expected .i32. got .f32." "" { target *-*-* } .-1 } + } +} + +fn main() { + let a; + a = Bar::::baz(123f32); +} diff --git a/gcc/testsuite/rust/compile/traits4.rs b/gcc/testsuite/rust/compile/traits4.rs new file mode 100644 index 00000000000..486301d6136 --- /dev/null +++ b/gcc/testsuite/rust/compile/traits4.rs @@ -0,0 +1,16 @@ +trait Foo { + const A: i32; + + fn test(self); +} + +struct Bar; +impl Foo for Bar { + // { dg-error "missing A in implementation of trait .Foo." "" { target *-*-* } .-1 } + fn test(self) {} +} + +fn main() { + let a = Bar; + a.test(); +} diff --git a/gcc/testsuite/rust/compile/traits5.rs b/gcc/testsuite/rust/compile/traits5.rs new file mode 100644 index 00000000000..8b2fb9bc10d --- /dev/null +++ b/gcc/testsuite/rust/compile/traits5.rs @@ -0,0 +1,9 @@ +trait Foo { + const A: i32; + + fn test(self); +} + +struct Bar; +impl Foo for Bar {} +// { dg-error "missing A, test in implementation of trait .Foo." "" { target *-*-* } .-1 } diff --git a/gcc/testsuite/rust/compile/traits6.rs b/gcc/testsuite/rust/compile/traits6.rs new file mode 100644 index 00000000000..3579b5a0842 --- /dev/null +++ b/gcc/testsuite/rust/compile/traits6.rs @@ -0,0 +1,15 @@ +trait Foo { + fn default() -> i32; +} + +struct Bar(i32); + +fn type_bound_test() -> i32 { + T::default() +} + +fn main() { + let a; + a = type_bound_test::(); + // { dg-error "bounds not satisfied for Bar" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/traits7.rs b/gcc/testsuite/rust/compile/traits7.rs new file mode 100644 index 00000000000..825553ce496 --- /dev/null +++ b/gcc/testsuite/rust/compile/traits7.rs @@ -0,0 +1,24 @@ +trait Foo { + fn default() -> i32; +} + +trait Bar { + fn not_default() -> i32; +} + +struct Test(i32); + +impl Foo for Test { + fn default() -> i32 { + 1234 + } +} + +fn type_bound_test() -> i32 { + T::default() +} + +fn main() { + let a = type_bound_test::(); + // { dg-error "bounds not satisfied for Test" "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/traits8.rs b/gcc/testsuite/rust/compile/traits8.rs new file mode 100644 index 00000000000..b22590a52bb --- /dev/null +++ b/gcc/testsuite/rust/compile/traits8.rs @@ -0,0 +1,35 @@ +trait A { + fn get(self) -> f64; +} + +trait B { + fn get(self) -> u8; +} + +struct Foo(u8, f64); + +impl A for Foo { + fn get(self) -> f64 { + self.1 + } +} + +impl B for Foo { + fn get(self) -> u8 { + self.0 + } +} + +fn main() { + let _a; + _a = Foo(123, 456f64); + + let _b: f64; + _b = ::get(_a); + + let _a; + _a = Foo(123, 456f64); + + let _c: u8; + _c = ::get(_a) +} diff --git a/gcc/testsuite/rust/compile/traits9.rs b/gcc/testsuite/rust/compile/traits9.rs new file mode 100644 index 00000000000..e1aef5397fc --- /dev/null +++ b/gcc/testsuite/rust/compile/traits9.rs @@ -0,0 +1,13 @@ +struct Foo(i32); +trait Bar { + fn baz(&self); +} + +fn main() { + let a; + a = Foo(123); + + let b: &dyn Bar = &a; + // { dg-error "bounds not satisfied for Foo .Bar. is not satisfied" "" { target *-*-* } .-1 } + // { dg-error "expected" "" { target *-*-* } .-2 } +} diff --git a/gcc/testsuite/rust/compile/tuple1.rs b/gcc/testsuite/rust/compile/tuple1.rs new file mode 100644 index 00000000000..84179b13727 --- /dev/null +++ b/gcc/testsuite/rust/compile/tuple1.rs @@ -0,0 +1,5 @@ +fn main() { + let a: (i32, bool) = (123, 123); // { dg-error "expected .bool. got .." } + let b; + b = (456, 5f32); +} diff --git a/gcc/testsuite/rust/compile/tuple_struct1.rs b/gcc/testsuite/rust/compile/tuple_struct1.rs new file mode 100644 index 00000000000..2f4cb4a353b --- /dev/null +++ b/gcc/testsuite/rust/compile/tuple_struct1.rs @@ -0,0 +1,8 @@ +struct Foo { + one: i32, + two: i32, +} + +fn main() { + let a = Foo(1, 2); // { dg-error "expected function, tuple struct or tuple variant, found struct 'Foo'" } +} diff --git a/gcc/testsuite/rust/compile/tuple_struct2.rs b/gcc/testsuite/rust/compile/tuple_struct2.rs new file mode 100644 index 00000000000..1fc18968577 --- /dev/null +++ b/gcc/testsuite/rust/compile/tuple_struct2.rs @@ -0,0 +1,5 @@ +struct Bar(i32, i32, bool); + +fn main() { + let a = Bar(1, 2); // { dg-error "unexpected number of arguments 2 expected 3" } +} diff --git a/gcc/testsuite/rust/compile/tuple_struct3.rs b/gcc/testsuite/rust/compile/tuple_struct3.rs new file mode 100644 index 00000000000..4af66b8370e --- /dev/null +++ b/gcc/testsuite/rust/compile/tuple_struct3.rs @@ -0,0 +1,6 @@ +struct Foo(i32, i32, bool); + +fn main() { + let c = Foo(1, 2f32, true); + // { dg-error "expected .i32. got .f32." "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/type-alias1.rs b/gcc/testsuite/rust/compile/type-alias1.rs new file mode 100644 index 00000000000..c7d7048246a --- /dev/null +++ b/gcc/testsuite/rust/compile/type-alias1.rs @@ -0,0 +1,6 @@ +type TypeAlias = (i32, u32); + +fn main() { + let a: TypeAlias; + a = (123, 456f32); // { dg-error "expected .u32. got .f32." } +} diff --git a/gcc/testsuite/rust/compile/type-bindings1.rs b/gcc/testsuite/rust/compile/type-bindings1.rs new file mode 100644 index 00000000000..ad85ed97ecb --- /dev/null +++ b/gcc/testsuite/rust/compile/type-bindings1.rs @@ -0,0 +1,10 @@ +struct Foo(A, B); + +fn main() { + let a; + a = Foo::(123f32); + // { dg-error "associated type bindings are not allowed here" "" { target *-*-* } .-1 } + // { dg-error {failed to type resolve expression} "" { target *-*-* } .-2 } + // { dg-error {Failed to resolve expression of function call} "" { target *-*-* } .-3 } + // { duplicate _dg-error {failed to type resolve expression} "" { target *-*-* } .-4 } +} diff --git a/gcc/testsuite/rust/compile/unary_negation.rs b/gcc/testsuite/rust/compile/unary_negation.rs new file mode 100644 index 00000000000..848643f0bd2 --- /dev/null +++ b/gcc/testsuite/rust/compile/unary_negation.rs @@ -0,0 +1,9 @@ +fn main() { + let a: i32 = -1; + let b: i32 = 3 - -1; + let c: bool = !false; + let d: i32 = !3; + + let e: f32 = -true; // // { dg-error "cannot apply unary - to bool" } + // { dg-error {failed to type resolve expression} "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/unary_not.rs b/gcc/testsuite/rust/compile/unary_not.rs new file mode 100644 index 00000000000..b0a3dafbbd0 --- /dev/null +++ b/gcc/testsuite/rust/compile/unary_not.rs @@ -0,0 +1,9 @@ +fn main() { + let a: i32 = -1; + let b: i32 = 3 - -1; + let c: bool = !false; + let d: i32 = !3; + + let e: f32 = !5f32; // { dg-error "cannot apply unary '!' to f32" } + // { dg-error {failed to type resolve expression} "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/unconstrained_type_param.rs b/gcc/testsuite/rust/compile/unconstrained_type_param.rs new file mode 100644 index 00000000000..c4aaa10146f --- /dev/null +++ b/gcc/testsuite/rust/compile/unconstrained_type_param.rs @@ -0,0 +1,12 @@ +struct Foo(T, bool); + +impl Foo { + // { dg-error "unconstrained type parameter" "" { target *-*-* } .-1 } + fn test() -> Y { + 123 + } +} + +fn main() { + let a = Foo::test(); +} diff --git a/gcc/testsuite/rust/compile/unicode_escape.rs b/gcc/testsuite/rust/compile/unicode_escape.rs new file mode 100644 index 00000000000..39b91d8a95c --- /dev/null +++ b/gcc/testsuite/rust/compile/unicode_escape.rs @@ -0,0 +1,60 @@ +fn main () +{ + // Braces are required + let _cbl = '\u013'; // { dg-error "unicode escape" } + let _sbl = "\u013"; //{ dg-error "unicode escape" } + + // One to six hex digits + let _c0 = '\u{}'; // { dg-error "unicode escape" } + let _c1 = '\u{0}'; + let _c2 = '\u{00}'; + let _c3 = '\u{000}'; + let _c4 = '\u{0000}'; + let _c5 = '\u{00000}'; + let _c6 = '\u{000000}'; + let _c7 = '\u{0000000}'; // { dg-error "unicode escape" } + + let _s0 = "\u{}"; // { dg-error "unicode escape" } + let _s1 = "\u{0}"; + let _s2 = "\u{00}"; + let _s3 = "\u{000}"; + let _s4 = "\u{0000}"; + let _s5 = "\u{00000}"; + let _s6 = "\u{000000}"; + let _s7 = "\u{0000000}"; // { dg-error "unicode escape" } + + // Underscores OK except for start + let _c_ = '\u{00___01__0_1_}'; + let _s_ = "\u{00___01__0_1_}"; + let _c__ = '\u{_00__01__0_}'; // { dg-error "unicode escape" } + let _s__ = "\u{_00__01__0_}"; // { dg-error "unicode escape" } + + // Must be hex chars + let _chex = '\u{hex}'; // { dg-error "unicode escape" } + let _shex = '\u{hex}'; // { dg-error "unicode escape" } + + // Only valid from 0x0 to 0xD7FF and from 0xE000 to 0x10FFF + let _cd7ff = '\u{D7FF}'; + let _sd7ff = "\u{D7FF}"; + let _cd800 = '\u{D800}'; // { dg-error "unicode escape" } + let _sd800 = "\u{D800}"; // { dg-error "unicode escape" } + + let _cdfff = '\u{DFFF}'; // { dg-error "unicode escape" } + let _sdfff = "\u{DFFF}"; // { dg-error "unicode escape" } + let _ce000 = '\u{E000}'; + let _se000 = "\u{E000}"; + + let _clast = '\u{10FFFF}'; + let _slast = "\u{10FFFF}"; + let _clast1 = '\u{110000}'; // { dg-error "unicode escape" } + let _slast1 = "\u{110000}"; // { dg-error "unicode escape" } + + let _cffffff = '\u{FFFFFF}'; // { dg-error "unicode escape" } + let _sffffff = "\u{FFFFFF}"; // { dg-error "unicode escape" } + + // unicode escapes cannot be used in bytes or byte strings. + // Except in raw byte strings (where they aren't escapes). + let _bc = b'\u{000A}'; // { dg-error "unicode escape" } + let _bs = b"\u{000A}"; // { dg-error "unicode escape" } + let _rbs = br"\u{000A}"; +} diff --git a/gcc/testsuite/rust/compile/unsafe1.rs b/gcc/testsuite/rust/compile/unsafe1.rs new file mode 100644 index 00000000000..9cd3f6b4bf2 --- /dev/null +++ b/gcc/testsuite/rust/compile/unsafe1.rs @@ -0,0 +1,14 @@ +fn foo(_a: &i32) {} +fn bar(_a: i32) {} + +static mut a: i32 = 15; + +fn main() { + foo(&a); // { dg-error "use of mutable static" } + bar(a); // { dg-error "use of mutable static" } + + unsafe { + foo(&a); + bar(a); + } +} diff --git a/gcc/testsuite/rust/compile/unsafe10.rs b/gcc/testsuite/rust/compile/unsafe10.rs new file mode 100644 index 00000000000..6b6be06b908 --- /dev/null +++ b/gcc/testsuite/rust/compile/unsafe10.rs @@ -0,0 +1,12 @@ +extern "rust-intrinsic" { + pub fn rotate_left(l: T, r: T) -> T; +} + +fn main() -> i32 { + let a = 15; + let b = 15; + + let _ = rotate_left(a, b); + + 0 +} diff --git a/gcc/testsuite/rust/compile/unsafe2.rs b/gcc/testsuite/rust/compile/unsafe2.rs new file mode 100644 index 00000000000..e03e4bc59f4 --- /dev/null +++ b/gcc/testsuite/rust/compile/unsafe2.rs @@ -0,0 +1,16 @@ +fn foo(_a: &i32) {} +fn bar(_a: i32) {} + +mod inner { + pub static mut a: i32 = 15; +} + +fn main() { + foo(&inner::a); // { dg-error "use of mutable static" } + bar(inner::a); // { dg-error "use of mutable static" } + + unsafe { + foo(&inner::a); + bar(inner::a); + } +} diff --git a/gcc/testsuite/rust/compile/unsafe3.rs b/gcc/testsuite/rust/compile/unsafe3.rs new file mode 100644 index 00000000000..56aec76008a --- /dev/null +++ b/gcc/testsuite/rust/compile/unsafe3.rs @@ -0,0 +1,10 @@ +extern "C" { + static VALUE: char; +} + +fn main() { + let _ = VALUE; // { dg-error "use of extern static" } + unsafe { + let _ = VALUE; + } +} diff --git a/gcc/testsuite/rust/compile/unsafe4.rs b/gcc/testsuite/rust/compile/unsafe4.rs new file mode 100644 index 00000000000..7d1356bc3e5 --- /dev/null +++ b/gcc/testsuite/rust/compile/unsafe4.rs @@ -0,0 +1,29 @@ +fn foo() -> i32 { + let a = 15; + let p_a = &a as *const i32; + + unsafe { *p_a } +} + +unsafe fn bar() -> i32 { + let a = 15; + let p_a = &a as *const i32; + + *p_a +} + +fn baz() -> i32 { + let a = 15; + let p_a = &a as *const i32; + + *p_a // { dg-error "dereference of raw pointer" } +} + +unsafe fn qux() -> i32 { + let a = 15; + let p_a = &a as *const i32; + + unsafe {} + + *p_a +} diff --git a/gcc/testsuite/rust/compile/unsafe5.rs b/gcc/testsuite/rust/compile/unsafe5.rs new file mode 100644 index 00000000000..35990f6ee9f --- /dev/null +++ b/gcc/testsuite/rust/compile/unsafe5.rs @@ -0,0 +1,4 @@ +fn main() { + let b = 15; + let c = *(&b as *const i32); // { dg-error "dereference of raw pointer" } +} diff --git a/gcc/testsuite/rust/compile/unsafe6.rs b/gcc/testsuite/rust/compile/unsafe6.rs new file mode 100644 index 00000000000..cf4b75456e4 --- /dev/null +++ b/gcc/testsuite/rust/compile/unsafe6.rs @@ -0,0 +1,14 @@ +unsafe fn foo() {} +unsafe fn bar() { + foo(); +} + +fn main() { + foo(); // { dg-error "call to unsafe function" } + bar(); // { dg-error "call to unsafe function" } + + unsafe { + foo(); + bar(); + } +} diff --git a/gcc/testsuite/rust/compile/unsafe7.rs b/gcc/testsuite/rust/compile/unsafe7.rs new file mode 100644 index 00000000000..a6b69e1ac37 --- /dev/null +++ b/gcc/testsuite/rust/compile/unsafe7.rs @@ -0,0 +1,9 @@ +extern "C" { + fn printf(fmt: *const i8, ...); +} + +fn main() { + let s = "hey\0"; + + printf(s as *const str as *const i8); // { dg-error "call to extern function" } +} diff --git a/gcc/testsuite/rust/compile/unsafe8.rs b/gcc/testsuite/rust/compile/unsafe8.rs new file mode 100644 index 00000000000..03fe4910c97 --- /dev/null +++ b/gcc/testsuite/rust/compile/unsafe8.rs @@ -0,0 +1,14 @@ +struct S; + +impl S { + unsafe fn foo(self) {} +} + +fn main() { + let s = S; + s.foo(); // { dg-error "call to unsafe method" } + + unsafe { + s.foo(); + } +} diff --git a/gcc/testsuite/rust/compile/unsafe9.rs b/gcc/testsuite/rust/compile/unsafe9.rs new file mode 100644 index 00000000000..fb46c8ffde3 --- /dev/null +++ b/gcc/testsuite/rust/compile/unsafe9.rs @@ -0,0 +1,10 @@ +union U { + a: i32, + b: f32, + c: u8, +} + +fn main() { + let u = U { a: 14 }; + let _ = u.a; // { dg-error "access to union" } +} diff --git a/gcc/testsuite/rust/compile/unterminated_c_comment.rs b/gcc/testsuite/rust/compile/unterminated_c_comment.rs new file mode 100644 index 00000000000..619b7b7024d --- /dev/null +++ b/gcc/testsuite/rust/compile/unterminated_c_comment.rs @@ -0,0 +1,2 @@ +// { dg-error "unexpected EOF while looking for end of comment" "" { target *-*-* } .+1 } +/* This comment needs closure :) ! diff --git a/gcc/testsuite/rust/compile/use_1.rs b/gcc/testsuite/rust/compile/use_1.rs new file mode 100644 index 00000000000..94b96321a63 --- /dev/null +++ b/gcc/testsuite/rust/compile/use_1.rs @@ -0,0 +1,16 @@ +mod frob {} + +use foo::bar::baz; // { dg-error "cannot find simple path segment .foo." } +use frob::ulator; // { dg-error "cannot find simple path segment .ulator." } + +mod sain { + mod doux {} + + mod dron {} +} + +use not_sain::*; // { dg-error "cannot find simple path segment .not_sain." } + +use sain::*; +use sain::{doux, dron}; +use sain::{doux, dron, graal}; // { dg-error "cannot find simple path segment .graal." } diff --git a/gcc/testsuite/rust/compile/usize1.rs b/gcc/testsuite/rust/compile/usize1.rs new file mode 100644 index 00000000000..b1c8fe86473 --- /dev/null +++ b/gcc/testsuite/rust/compile/usize1.rs @@ -0,0 +1,6 @@ +fn main() { + let a = [1, 2, 3]; + let b: u32 = 1; + let c = a[b]; // { dg-error "the type ...integer..CAPACITY.. cannot be indexed by .u32." } + // { dg-error {failed to type resolve expression} "" { target *-*-* } .-1 } +} diff --git a/gcc/testsuite/rust/compile/xfail/lifetime_param.rs b/gcc/testsuite/rust/compile/xfail/lifetime_param.rs new file mode 100644 index 00000000000..306fca0b3c5 --- /dev/null +++ b/gcc/testsuite/rust/compile/xfail/lifetime_param.rs @@ -0,0 +1,11 @@ +// { dg-excess-errors "warnings" } + +// { dg-error "lifetime not defined" "#359" { xfail *-*-* } .+1 } +fn lifetime_undefined(t: &'a str) -> &'a str { + t +} + +// { dg-error "lifetime not defined" "#359" { xfail *-*-* } .+1 } +fn lifetime_undefined_bis<'a>(t: &'a str)-> &'b str { + t +} diff --git a/gcc/testsuite/rust/compile/xfail/struct_field_vis.rs b/gcc/testsuite/rust/compile/xfail/struct_field_vis.rs new file mode 100644 index 00000000000..a28729e6208 --- /dev/null +++ b/gcc/testsuite/rust/compile/xfail/struct_field_vis.rs @@ -0,0 +1,15 @@ +// { dg-xfail-if "pub visibility not supported #432" *-*-* } + +mod foomod { + pub struct Foo { + pub f: i32, + pub g: u32, + } +} + +fn test() -> foomod::Foo { + foomod::Foo{ + f:1, + g:3, + } +} diff --git a/gcc/testsuite/rust/compile/xfail/xfail.exp b/gcc/testsuite/rust/compile/xfail/xfail.exp new file mode 100644 index 00000000000..5fb6203bb31 --- /dev/null +++ b/gcc/testsuite/rust/compile/xfail/xfail.exp @@ -0,0 +1,63 @@ +# Copyright (C) 2021-2022 Free Software Foundation, Inc. + +# This program 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 of the License, or +# (at your option) any later version. +# +# This program 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 +# . + +# Compile tests, no torture testing. +# +# These tests are used to keep track of known limitations : +# 1- tests that are incorrecly build instead of being rejected +# 2- tests that are build to an incorrect result +# 3- tests that are rejected instead of being correctly build +# +# Not currently supported here: +# - tests that are exhibiting incorrect behavior at runtime +# +# Here's how to annotate tests for each cases: +# +# 1- test is successfuly build instead of being rejected +# +# Expected behavior: a specific error rejecting the test +# Observed behavior: error not present +# Use dg-error and mark the test xfail and add reference to corresponding issue. +# { dg-error "lifetime not defined" "#359" { xfail *-*-* } } +# +# 2- test is successfuly build but result is incorrect +# +# Expected behavior: test is correctly build and has specific property +# Observed behavior: test is correctly build but is missing the specific property +# Depends on the property. For example, if the property can be checked in the assembly file, use dg-final + xfail. +# { dg-final { scan-assembler "given_string_missing_in_assembly_" "#1234" { xfail *-*-* } } } +# +# 3- test is rejected instead of being correctly build +# +# Expected behavior: test is successfully build +# Observed behavior: the test is rejected with an error +# Use dg-bogus + xfail to match the bogus error message, or use dg-xfail-if if it's harder to match a specific error. + +# Load support procs. +load_lib rust-dg.exp + +# Initialize `dg'. +dg-init + +# Main loop. +set saved-dg-do-what-default ${dg-do-what-default} + +set dg-do-what-default "compile" +dg-runtest [lsort [glob -nocomplain $srcdir/$subdir/*.rs]] "" "" +set dg-do-what-default ${saved-dg-do-what-default} + +# All done. +dg-finish From patchwork Wed Aug 24 11:59:25 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: herron.philip@googlemail.com X-Patchwork-Id: 56982 Return-Path: X-Original-To: patchwork@sourceware.org Delivered-To: patchwork@sourceware.org Received: from server2.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id DF611394D8EC for ; Wed, 24 Aug 2022 12:01:55 +0000 (GMT) X-Original-To: gcc-patches@gcc.gnu.org Delivered-To: gcc-patches@gcc.gnu.org Received: from mail-wr1-x429.google.com (mail-wr1-x429.google.com [IPv6:2a00:1450:4864:20::429]) by sourceware.org (Postfix) with ESMTPS id E1EEF384F027; Wed, 24 Aug 2022 12:00:37 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.1 sourceware.org E1EEF384F027 Authentication-Results: sourceware.org; dmarc=pass (p=quarantine dis=none) header.from=googlemail.com Authentication-Results: sourceware.org; spf=pass smtp.mailfrom=googlemail.com Received: by mail-wr1-x429.google.com with SMTP id bs25so20503508wrb.2; Wed, 24 Aug 2022 05:00:37 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=googlemail.com; s=20210112; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc; bh=ToySAx65SIKAJDX8LQ2D5Y+sKCaHzlfNDg4SctYvC5k=; b=CXbQUZTB0Irw7HqofvirUJJepvRUK/+KUekst7Gqn90XrulVV+eIamiroNqz3Hnj2J SR8uQQFM4HA0ePmu32v+Dan7wVbqntnjb/qlElfYNB1aCNDPqwx7QpIYor8lXlZjaaWd UNywJoyHZT0yhaxy2cs7uOJh4+bAYGccpETkeVgbPgNSYR3tcBkbwK9oIrDnn5VzhtuA yBhf47B12wQTmrMC7nouc73j8BkuWVTKFHEtnc1k2iY/tGdrzySAbG17SnrneSnvLj3C w8+IUhDPIP2A4WHgJpagelfdpGNYFpPeABLqR6rY1riU3fL3bWrA4XnEGSjtp/fs9jhN pQVg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc; bh=ToySAx65SIKAJDX8LQ2D5Y+sKCaHzlfNDg4SctYvC5k=; b=k+T6ifij51bCcKnVENY6dct08Mz/g51lgJx+VlG8YpuE9aW/3ZMk6DE5VRgODMKtmp +oam/qx3zkcHWEQ5w2Dg+Wi0dxiQ+4sXmRhgnl+yzMd+qL80yc4Ud8vdtK8cc2AN1P+c ODiI2/KltkXgGvyzKahuMu99/vTGJZjKtBGdhNcaB6AluzHCFu8+Z8wrJ4Vxb7l02GsY M5K1gDB8aui6uxiRtwk/wGAava6ponOfyEElZJuklc4OAjnbzqhZkXTkoFyuNrOTOReU /V5TeC15fwDM4qThh5sXAsh5Q0V2kW4uX5ZMBFGfhCRU4BMevI7A5aJvu2OTO0kVrXNN WZcw== X-Gm-Message-State: ACgBeo0N6Ra4fkXO6cQ/62ra3q97OD8Xq+KHhcZGipPdR1nHZFPkyBz+ SaGQyAV5A1ImT/fjaB0BzAk68V9dHqM= X-Google-Smtp-Source: AA6agR47rHWn1kt8WmWZhXpCgU5uCJgKSBRkQ1xzlRSaTIy56/jAsRLhpgoqyzG79oiFBv1NaTyCvA== X-Received: by 2002:a5d:6a50:0:b0:225:5dd6:873f with SMTP id t16-20020a5d6a50000000b002255dd6873fmr6497346wrw.101.1661342433777; Wed, 24 Aug 2022 05:00:33 -0700 (PDT) Received: from localhost.localdomain ([86.14.124.218]) by smtp.gmail.com with ESMTPSA id cc19-20020a5d5c13000000b0022571d43d32sm1697676wrb.21.2022.08.24.05.00.32 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 24 Aug 2022 05:00:33 -0700 (PDT) From: herron.philip@googlemail.com X-Google-Original-From: philip.herron@embecosm.com To: gcc-patches@gcc.gnu.org Subject: [PATCH Rust front-end v2 06/37] gccrs: Add execution test cases Date: Wed, 24 Aug 2022 12:59:25 +0100 Message-Id: <20220824115956.737931-7-philip.herron@embecosm.com> X-Mailer: git-send-email 2.25.1 In-Reply-To: <20220824115956.737931-1-philip.herron@embecosm.com> References: <20220824115956.737931-1-philip.herron@embecosm.com> MIME-Version: 1.0 X-Spam-Status: No, score=-11.4 required=5.0 tests=BAYES_00, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, DKIM_VALID_EF, FREEMAIL_FROM, GIT_PATCH_0, KAM_SHORT, RCVD_IN_DNSWL_NONE, SPF_HELO_NONE, SPF_PASS, TXREP, T_SCC_BODY_TEXT_LINE autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on server2.sourceware.org X-BeenThere: gcc-patches@gcc.gnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: Gcc-patches mailing list List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Reply-To: philip.herron@embecosm.com Cc: =?utf-8?q?Marc_Poulhi=C3=A8s?= , Philip Herron , Mark Wielaard , Arthur Cohen , gcc-rust@gcc.gnu.org, Thomas Schwinge Errors-To: gcc-patches-bounces+patchwork=sourceware.org@gcc.gnu.org Sender: "Gcc-patches" From: Philip Herron This is similar to the compile/torture/*.rs test cases but all of these are dg-execute testcases so they get compiled, linked and executed by default, all the while being compiled with the matrix of torture options. The only caveat here is that currently gccrs does not currently support the main shim yet so we have a C-style main function here returning zero which is not supported in Rustc. Co-authored-by: Arthur Cohen Co-authored-by: Thomas Schwinge Co-authored-by: Mark Wielaard Co-authored-by: Marc Poulhiès --- .../rust/execute/torture/block_expr1.rs | 8 + .../rust/execute/torture/builtin_macro_cfg.rs | 32 ++++ .../execute/torture/builtin_macro_concat.rs | 29 +++ .../rust/execute/torture/builtin_macro_env.rs | 31 ++++ .../torture/builtin_macro_include_bytes.rs | 46 +++++ .../torture/builtin_macro_include_str.rs | 27 +++ .../execute/torture/builtin_macro_line.rs | 25 +++ .../rust/execute/torture/builtin_macros1.rs | 21 +++ .../rust/execute/torture/builtin_macros3.rs | 28 +++ gcc/testsuite/rust/execute/torture/cfg1.rs | 32 ++++ gcc/testsuite/rust/execute/torture/cfg2.rs | 31 ++++ gcc/testsuite/rust/execute/torture/cfg3.rs | 37 ++++ gcc/testsuite/rust/execute/torture/cfg4.rs | 38 ++++ gcc/testsuite/rust/execute/torture/cfg5.rs | 13 ++ .../rust/execute/torture/coercion1.rs | 41 +++++ .../rust/execute/torture/coercion2.rs | 39 ++++ .../rust/execute/torture/const_fold1.rs | 13 ++ .../rust/execute/torture/const_fold2.rs | 16 ++ .../execute/torture/copy_nonoverlapping1.rs | 17 ++ .../rust/execute/torture/empty_main.rs | 3 + .../rust/execute/torture/execute.exp | 33 ++++ .../rust/execute/torture/exit_error.rs | 5 + .../rust/execute/torture/extern_mod4.rs | 19 ++ gcc/testsuite/rust/execute/torture/func1.rs | 5 + .../rust/execute/torture/helloworld1.rs | 15 ++ .../rust/execute/torture/helloworld2.rs | 15 ++ .../rust/execute/torture/include.txt | 1 + gcc/testsuite/rust/execute/torture/index1.rs | 28 +++ .../rust/execute/torture/issue-1120.rs | 123 +++++++++++++ .../rust/execute/torture/issue-1133.rs | 146 +++++++++++++++ .../rust/execute/torture/issue-1198.rs | 75 ++++++++ .../rust/execute/torture/issue-1231.rs | 36 ++++ .../rust/execute/torture/issue-1232.rs | 159 ++++++++++++++++ .../rust/execute/torture/issue-1249.rs | 39 ++++ .../rust/execute/torture/issue-1436.rs | 172 ++++++++++++++++++ .../rust/execute/torture/issue-1496.rs | 75 ++++++++ .../rust/execute/torture/issue-647.rs | 33 ++++ .../rust/execute/torture/issue-845.rs | 47 +++++ .../rust/execute/torture/issue-851.rs | 35 ++++ .../rust/execute/torture/issue-858.rs | 32 ++++ .../rust/execute/torture/issue-976.rs | 14 ++ .../rust/execute/torture/issue-995.rs | 9 + gcc/testsuite/rust/execute/torture/macros1.rs | 13 ++ .../rust/execute/torture/macros10.rs | 22 +++ .../rust/execute/torture/macros11.rs | 25 +++ .../rust/execute/torture/macros12.rs | 22 +++ .../rust/execute/torture/macros13.rs | 22 +++ .../rust/execute/torture/macros14.rs | 22 +++ .../rust/execute/torture/macros16.rs | 14 ++ .../rust/execute/torture/macros17.rs | 17 ++ .../rust/execute/torture/macros18.rs | 14 ++ .../rust/execute/torture/macros19.rs | 14 ++ gcc/testsuite/rust/execute/torture/macros2.rs | 40 ++++ .../rust/execute/torture/macros20.rs | 14 ++ .../rust/execute/torture/macros21.rs | 15 ++ .../rust/execute/torture/macros22.rs | 27 +++ .../rust/execute/torture/macros23.rs | 19 ++ .../rust/execute/torture/macros24.rs | 9 + .../rust/execute/torture/macros25.rs | 13 ++ .../rust/execute/torture/macros26.rs | 12 ++ .../rust/execute/torture/macros27.rs | 24 +++ .../rust/execute/torture/macros28.rs | 13 ++ .../rust/execute/torture/macros29.rs | 24 +++ gcc/testsuite/rust/execute/torture/macros3.rs | 61 +++++++ .../rust/execute/torture/macros30.rs | 25 +++ .../rust/execute/torture/macros31.rs | 32 ++++ gcc/testsuite/rust/execute/torture/macros4.rs | 15 ++ gcc/testsuite/rust/execute/torture/macros5.rs | 13 ++ gcc/testsuite/rust/execute/torture/macros6.rs | 12 ++ gcc/testsuite/rust/execute/torture/macros7.rs | 28 +++ gcc/testsuite/rust/execute/torture/macros8.rs | 27 +++ gcc/testsuite/rust/execute/torture/macros9.rs | 28 +++ gcc/testsuite/rust/execute/torture/match1.rs | 58 ++++++ gcc/testsuite/rust/execute/torture/match2.rs | 41 +++++ gcc/testsuite/rust/execute/torture/match3.rs | 51 ++++++ .../rust/execute/torture/match_bool1.rs | 49 +++++ .../rust/execute/torture/match_byte1.rs | 56 ++++++ .../rust/execute/torture/match_char1.rs | 56 ++++++ .../rust/execute/torture/match_int1.rs | 109 +++++++++++ .../rust/execute/torture/match_loop1.rs | 56 ++++++ .../rust/execute/torture/match_range1.rs | 37 ++++ .../rust/execute/torture/match_range2.rs | 45 +++++ .../rust/execute/torture/match_tuple1.rs | 45 +++++ gcc/testsuite/rust/execute/torture/method1.rs | 27 +++ gcc/testsuite/rust/execute/torture/method2.rs | 76 ++++++++ gcc/testsuite/rust/execute/torture/method3.rs | 78 ++++++++ gcc/testsuite/rust/execute/torture/method4.rs | 78 ++++++++ gcc/testsuite/rust/execute/torture/mod1.rs | 21 +++ .../rust/execute/torture/modules/mod.rs | 3 + .../execute/torture/operator_overload_1.rs | 36 ++++ .../execute/torture/operator_overload_10.rs | 75 ++++++++ .../execute/torture/operator_overload_11.rs | 37 ++++ .../execute/torture/operator_overload_12.rs | 31 ++++ .../execute/torture/operator_overload_2.rs | 38 ++++ .../execute/torture/operator_overload_3.rs | 55 ++++++ .../execute/torture/operator_overload_4.rs | 33 ++++ .../execute/torture/operator_overload_5.rs | 33 ++++ .../execute/torture/operator_overload_6.rs | 37 ++++ .../execute/torture/operator_overload_7.rs | 42 +++++ .../execute/torture/operator_overload_8.rs | 58 ++++++ .../execute/torture/operator_overload_9.rs | 58 ++++++ .../rust/execute/torture/slice-magic.rs | 106 +++++++++++ .../rust/execute/torture/slice-magic2.rs | 106 +++++++++++ gcc/testsuite/rust/execute/torture/slice1.rs | 27 +++ .../rust/execute/torture/str-layout1.rs | 57 ++++++ .../rust/execute/torture/str-zero.rs | 26 +++ gcc/testsuite/rust/execute/torture/trait1.rs | 52 ++++++ gcc/testsuite/rust/execute/torture/trait10.rs | 41 +++++ gcc/testsuite/rust/execute/torture/trait11.rs | 38 ++++ gcc/testsuite/rust/execute/torture/trait12.rs | 38 ++++ gcc/testsuite/rust/execute/torture/trait13.rs | 48 +++++ gcc/testsuite/rust/execute/torture/trait2.rs | 37 ++++ gcc/testsuite/rust/execute/torture/trait3.rs | 43 +++++ gcc/testsuite/rust/execute/torture/trait4.rs | 34 ++++ gcc/testsuite/rust/execute/torture/trait5.rs | 39 ++++ gcc/testsuite/rust/execute/torture/trait6.rs | 39 ++++ gcc/testsuite/rust/execute/torture/trait7.rs | 39 ++++ gcc/testsuite/rust/execute/torture/trait8.rs | 39 ++++ gcc/testsuite/rust/execute/torture/trait9.rs | 35 ++++ .../rust/execute/torture/transmute1.rs | 23 +++ .../rust/execute/torture/wrapping_op1.rs | 14 ++ .../rust/execute/torture/wrapping_op2.rs | 20 ++ gcc/testsuite/rust/execute/xfail/macro1.rs | 32 ++++ 123 files changed, 4631 insertions(+) create mode 100644 gcc/testsuite/rust/execute/torture/block_expr1.rs create mode 100644 gcc/testsuite/rust/execute/torture/builtin_macro_cfg.rs create mode 100644 gcc/testsuite/rust/execute/torture/builtin_macro_concat.rs create mode 100644 gcc/testsuite/rust/execute/torture/builtin_macro_env.rs create mode 100644 gcc/testsuite/rust/execute/torture/builtin_macro_include_bytes.rs create mode 100644 gcc/testsuite/rust/execute/torture/builtin_macro_include_str.rs create mode 100644 gcc/testsuite/rust/execute/torture/builtin_macro_line.rs create mode 100644 gcc/testsuite/rust/execute/torture/builtin_macros1.rs create mode 100644 gcc/testsuite/rust/execute/torture/builtin_macros3.rs create mode 100644 gcc/testsuite/rust/execute/torture/cfg1.rs create mode 100644 gcc/testsuite/rust/execute/torture/cfg2.rs create mode 100644 gcc/testsuite/rust/execute/torture/cfg3.rs create mode 100644 gcc/testsuite/rust/execute/torture/cfg4.rs create mode 100644 gcc/testsuite/rust/execute/torture/cfg5.rs create mode 100644 gcc/testsuite/rust/execute/torture/coercion1.rs create mode 100644 gcc/testsuite/rust/execute/torture/coercion2.rs create mode 100644 gcc/testsuite/rust/execute/torture/const_fold1.rs create mode 100644 gcc/testsuite/rust/execute/torture/const_fold2.rs create mode 100644 gcc/testsuite/rust/execute/torture/copy_nonoverlapping1.rs create mode 100644 gcc/testsuite/rust/execute/torture/empty_main.rs create mode 100644 gcc/testsuite/rust/execute/torture/execute.exp create mode 100644 gcc/testsuite/rust/execute/torture/exit_error.rs create mode 100644 gcc/testsuite/rust/execute/torture/extern_mod4.rs create mode 100644 gcc/testsuite/rust/execute/torture/func1.rs create mode 100644 gcc/testsuite/rust/execute/torture/helloworld1.rs create mode 100644 gcc/testsuite/rust/execute/torture/helloworld2.rs create mode 100644 gcc/testsuite/rust/execute/torture/include.txt create mode 100644 gcc/testsuite/rust/execute/torture/index1.rs create mode 100644 gcc/testsuite/rust/execute/torture/issue-1120.rs create mode 100644 gcc/testsuite/rust/execute/torture/issue-1133.rs create mode 100644 gcc/testsuite/rust/execute/torture/issue-1198.rs create mode 100644 gcc/testsuite/rust/execute/torture/issue-1231.rs create mode 100644 gcc/testsuite/rust/execute/torture/issue-1232.rs create mode 100644 gcc/testsuite/rust/execute/torture/issue-1249.rs create mode 100644 gcc/testsuite/rust/execute/torture/issue-1436.rs create mode 100644 gcc/testsuite/rust/execute/torture/issue-1496.rs create mode 100644 gcc/testsuite/rust/execute/torture/issue-647.rs create mode 100644 gcc/testsuite/rust/execute/torture/issue-845.rs create mode 100644 gcc/testsuite/rust/execute/torture/issue-851.rs create mode 100644 gcc/testsuite/rust/execute/torture/issue-858.rs create mode 100644 gcc/testsuite/rust/execute/torture/issue-976.rs create mode 100644 gcc/testsuite/rust/execute/torture/issue-995.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros1.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros10.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros11.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros12.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros13.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros14.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros16.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros17.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros18.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros19.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros2.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros20.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros21.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros22.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros23.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros24.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros25.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros26.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros27.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros28.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros29.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros3.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros30.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros31.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros4.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros5.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros6.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros7.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros8.rs create mode 100644 gcc/testsuite/rust/execute/torture/macros9.rs create mode 100644 gcc/testsuite/rust/execute/torture/match1.rs create mode 100644 gcc/testsuite/rust/execute/torture/match2.rs create mode 100644 gcc/testsuite/rust/execute/torture/match3.rs create mode 100644 gcc/testsuite/rust/execute/torture/match_bool1.rs create mode 100644 gcc/testsuite/rust/execute/torture/match_byte1.rs create mode 100644 gcc/testsuite/rust/execute/torture/match_char1.rs create mode 100644 gcc/testsuite/rust/execute/torture/match_int1.rs create mode 100644 gcc/testsuite/rust/execute/torture/match_loop1.rs create mode 100644 gcc/testsuite/rust/execute/torture/match_range1.rs create mode 100644 gcc/testsuite/rust/execute/torture/match_range2.rs create mode 100644 gcc/testsuite/rust/execute/torture/match_tuple1.rs create mode 100644 gcc/testsuite/rust/execute/torture/method1.rs create mode 100644 gcc/testsuite/rust/execute/torture/method2.rs create mode 100644 gcc/testsuite/rust/execute/torture/method3.rs create mode 100644 gcc/testsuite/rust/execute/torture/method4.rs create mode 100644 gcc/testsuite/rust/execute/torture/mod1.rs create mode 100644 gcc/testsuite/rust/execute/torture/modules/mod.rs create mode 100644 gcc/testsuite/rust/execute/torture/operator_overload_1.rs create mode 100644 gcc/testsuite/rust/execute/torture/operator_overload_10.rs create mode 100644 gcc/testsuite/rust/execute/torture/operator_overload_11.rs create mode 100644 gcc/testsuite/rust/execute/torture/operator_overload_12.rs create mode 100644 gcc/testsuite/rust/execute/torture/operator_overload_2.rs create mode 100644 gcc/testsuite/rust/execute/torture/operator_overload_3.rs create mode 100644 gcc/testsuite/rust/execute/torture/operator_overload_4.rs create mode 100644 gcc/testsuite/rust/execute/torture/operator_overload_5.rs create mode 100644 gcc/testsuite/rust/execute/torture/operator_overload_6.rs create mode 100644 gcc/testsuite/rust/execute/torture/operator_overload_7.rs create mode 100644 gcc/testsuite/rust/execute/torture/operator_overload_8.rs create mode 100644 gcc/testsuite/rust/execute/torture/operator_overload_9.rs create mode 100644 gcc/testsuite/rust/execute/torture/slice-magic.rs create mode 100644 gcc/testsuite/rust/execute/torture/slice-magic2.rs create mode 100644 gcc/testsuite/rust/execute/torture/slice1.rs create mode 100644 gcc/testsuite/rust/execute/torture/str-layout1.rs create mode 100644 gcc/testsuite/rust/execute/torture/str-zero.rs create mode 100644 gcc/testsuite/rust/execute/torture/trait1.rs create mode 100644 gcc/testsuite/rust/execute/torture/trait10.rs create mode 100644 gcc/testsuite/rust/execute/torture/trait11.rs create mode 100644 gcc/testsuite/rust/execute/torture/trait12.rs create mode 100644 gcc/testsuite/rust/execute/torture/trait13.rs create mode 100644 gcc/testsuite/rust/execute/torture/trait2.rs create mode 100644 gcc/testsuite/rust/execute/torture/trait3.rs create mode 100644 gcc/testsuite/rust/execute/torture/trait4.rs create mode 100644 gcc/testsuite/rust/execute/torture/trait5.rs create mode 100644 gcc/testsuite/rust/execute/torture/trait6.rs create mode 100644 gcc/testsuite/rust/execute/torture/trait7.rs create mode 100644 gcc/testsuite/rust/execute/torture/trait8.rs create mode 100644 gcc/testsuite/rust/execute/torture/trait9.rs create mode 100644 gcc/testsuite/rust/execute/torture/transmute1.rs create mode 100644 gcc/testsuite/rust/execute/torture/wrapping_op1.rs create mode 100644 gcc/testsuite/rust/execute/torture/wrapping_op2.rs create mode 100644 gcc/testsuite/rust/execute/xfail/macro1.rs diff --git a/gcc/testsuite/rust/execute/torture/block_expr1.rs b/gcc/testsuite/rust/execute/torture/block_expr1.rs new file mode 100644 index 00000000000..d561f8cab59 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/block_expr1.rs @@ -0,0 +1,8 @@ +fn main() -> i32 { + let ret = { + 1; + 2; + 0 + }; + ret +} diff --git a/gcc/testsuite/rust/execute/torture/builtin_macro_cfg.rs b/gcc/testsuite/rust/execute/torture/builtin_macro_cfg.rs new file mode 100644 index 00000000000..fad2daef6bc --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/builtin_macro_cfg.rs @@ -0,0 +1,32 @@ +// { dg-additional-options "-w -frust-cfg=A" } +// { dg-output "A\n" } +#[rustc_builtin_macro] +macro_rules! cfg { + () => {{}}; +} + +extern "C" { + fn printf(fmt: *const i8, ...); +} + +fn print(s: &str) { + unsafe { + printf( + "%s\n" as *const str as *const i8, + s as *const str as *const i8, + ); + } +} + +fn main() -> i32 { + let cfg = cfg!(A); + if cfg { + print("A"); + } + let cfg = cfg!(B); + if cfg { + print("B"); + } + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/builtin_macro_concat.rs b/gcc/testsuite/rust/execute/torture/builtin_macro_concat.rs new file mode 100644 index 00000000000..9b33924f5a1 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/builtin_macro_concat.rs @@ -0,0 +1,29 @@ +// { dg-output "\ntest10btrue2.15\ntest10bfalse2.151\n" } +#[rustc_builtin_macro] +macro_rules! concat { + () => {{}}; +} + +extern "C" { + fn printf(fmt: *const i8, ...); +} + +fn print(s: &str) { + unsafe { + printf( + "%s\n" as *const str as *const i8, + s as *const str as *const i8, + ); + } +} + +fn main() -> i32 { + let a = concat!(); + let b = concat!("test", 10, 'b', true, 2.15); + let c = concat!("test", 10, 'b', false, 2.15, 1u64); + print(a); + print(b); + print(c); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/builtin_macro_env.rs b/gcc/testsuite/rust/execute/torture/builtin_macro_env.rs new file mode 100644 index 00000000000..a5c80b25728 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/builtin_macro_env.rs @@ -0,0 +1,31 @@ +// { dg-output "VALUE\nVALUE\n" } +// { dg-set-compiler-env-var ENV_MACRO_TEST "VALUE" } +#[rustc_builtin_macro] +macro_rules! env { + () => {{}}; +} + +extern "C" { + fn printf(fmt: *const i8, ...); +} + +fn print(s: &str) { + unsafe { + printf( + "%s\n" as *const str as *const i8, + s as *const str as *const i8, + ); + } +} + +fn main() -> i32 { + let val0 = env!("ENV_MACRO_TEST"); + + print(val0); + + let val1 = env!("ENV_MACRO_TEST",); + + print(val1); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/builtin_macro_include_bytes.rs b/gcc/testsuite/rust/execute/torture/builtin_macro_include_bytes.rs new file mode 100644 index 00000000000..087f0220de5 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/builtin_macro_include_bytes.rs @@ -0,0 +1,46 @@ +// { dg-output "104\n33\n1\n" } +#[rustc_builtin_macro] +macro_rules! include_bytes { + () => {{}}; +} + +extern "C" { + fn printf(s: *const i8, ...); +} + +fn print_int(value: i32) { + let s = "%d\n\0" as *const str as *const i8; + unsafe { + printf(s, value); + } +} + +fn main() -> i32 { + let bytes = include_bytes!("include.txt"); + + print_int(bytes[0] as i32); + print_int(bytes[14] as i32); + + let the_bytes = b"hello, include!\n"; + + let x = bytes[0] == the_bytes[0] + && bytes[1] == the_bytes[1] + && bytes[2] == the_bytes[2] + && bytes[3] == the_bytes[3] + && bytes[4] == the_bytes[4] + && bytes[5] == the_bytes[5] + && bytes[6] == the_bytes[6] + && bytes[7] == the_bytes[7] + && bytes[8] == the_bytes[8] + && bytes[9] == the_bytes[9] + && bytes[10] == the_bytes[10] + && bytes[11] == the_bytes[11] + && bytes[12] == the_bytes[12] + && bytes[13] == the_bytes[13] + && bytes[14] == the_bytes[14] + && bytes[15] == the_bytes[15]; + + print_int(x as i32); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/builtin_macro_include_str.rs b/gcc/testsuite/rust/execute/torture/builtin_macro_include_str.rs new file mode 100644 index 00000000000..6f9871d379c --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/builtin_macro_include_str.rs @@ -0,0 +1,27 @@ +// { dg-output "hello, include!\n" } +#[rustc_builtin_macro] +macro_rules! include_str { + () => {{}}; +} + +extern "C" { + fn printf(fmt: *const i8, ...); +} + +fn print(s: &str) { + unsafe { + printf( + "%s" as *const str as *const i8, + s as *const str as *const i8, + ); + } +} + +fn main() -> i32 { + // include_str! (and include_bytes!) allow for an optional trailing comma. + let my_str = include_str!("include.txt",); + + print(my_str); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/builtin_macro_line.rs b/gcc/testsuite/rust/execute/torture/builtin_macro_line.rs new file mode 100644 index 00000000000..02541ed52e2 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/builtin_macro_line.rs @@ -0,0 +1,25 @@ +// { dg-output "18\n21\n" } +extern "C" { + fn printf(fmt: *const i8, ...); +} + +fn print(s: u32) { + unsafe { + printf("%u\n\0" as *const str as *const i8, s); + } +} + +#[rustc_builtin_macro] +macro_rules! line { + () => {{}}; +} + +fn main() -> i32 { + let a = line!(); + print(a); + + let b = line!(); + print(b); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/builtin_macros1.rs b/gcc/testsuite/rust/execute/torture/builtin_macros1.rs new file mode 100644 index 00000000000..5976478e426 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/builtin_macros1.rs @@ -0,0 +1,21 @@ +// { dg-output "rust/execute/torture/builtin_macros1.rs" } +#[rustc_builtin_macro] +macro_rules! file { + () => {{}}; +} + +extern "C" { + fn printf(fmt: *const i8, ...); +} + +fn print(s: &str) { + unsafe { + printf("%s\n\0" as *const str as *const i8, s); + } +} + +fn main() -> i32 { + print(file!()); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/builtin_macros3.rs b/gcc/testsuite/rust/execute/torture/builtin_macros3.rs new file mode 100644 index 00000000000..24555cbdb8a --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/builtin_macros3.rs @@ -0,0 +1,28 @@ +// { dg-output "14\n42\n" } +#[rustc_builtin_macro] +macro_rules! column { + () => {{}}; +} + +extern "C" { + fn printf(fmt: *const i8, ...); +} + +fn print(s: u32) { + unsafe { + printf("%u\n\0" as *const str as *const i8, s); + } +} + +fn main() -> i32 { + let c0 = column!(); + + print(c0); + + let c1 = column!(); + + print(c1); + + 0 +} + diff --git a/gcc/testsuite/rust/execute/torture/cfg1.rs b/gcc/testsuite/rust/execute/torture/cfg1.rs new file mode 100644 index 00000000000..d3c56295503 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/cfg1.rs @@ -0,0 +1,32 @@ +// { dg-additional-options "-w -frust-cfg=A" } +// { dg-output "test1\n" } +extern "C" { + fn printf(s: *const i8, ...); +} + +#[cfg(A)] +fn test() { + unsafe { + let a = "test1\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } +} + +#[cfg(B)] +fn test() { + unsafe { + let a = "test2\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } +} + +fn main() -> i32 { + test(); + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/cfg2.rs b/gcc/testsuite/rust/execute/torture/cfg2.rs new file mode 100644 index 00000000000..5048bcb2791 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/cfg2.rs @@ -0,0 +1,31 @@ +// { dg-additional-options "-w -frust-cfg=A" } +// { dg-output "test1\n" } +extern "C" { + fn printf(s: *const i8, ...); +} + +fn test() { + #[cfg(A)] + unsafe { + let a = "test1\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + #[cfg(B)] + unsafe { + let a = "test2\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } +} + +fn main() -> i32 { + test(); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/cfg3.rs b/gcc/testsuite/rust/execute/torture/cfg3.rs new file mode 100644 index 00000000000..89312344b23 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/cfg3.rs @@ -0,0 +1,37 @@ +// { dg-additional-options "-w -frust-cfg=A" } +// { dg-output "test1\n" } +extern "C" { + fn printf(s: *const i8, ...); +} + +struct Foo(i32); +impl Foo { + #[cfg(A)] + fn test(&self) { + unsafe { + let a = "test1\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + } + + #[cfg(B)] + fn test(&self) { + unsafe { + let a = "test2\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + } +} + +fn main() -> i32 { + let a = Foo(123); + a.test(); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/cfg4.rs b/gcc/testsuite/rust/execute/torture/cfg4.rs new file mode 100644 index 00000000000..d1c2a22a0ff --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/cfg4.rs @@ -0,0 +1,38 @@ +// { dg-additional-options "-w -frust-cfg=A" } +// { dg-output "test1\ntest2\n" } +extern "C" { + fn printf(s: *const i8, ...); +} + +struct Foo(i32); +impl Foo { + #[cfg(A)] + fn test(&self) { + unsafe { + let a = "test1\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + } + + #[cfg(not(B))] + fn test2(&self) { + unsafe { + let a = "test2\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + } +} + +fn main() -> i32 { + let a = Foo(123); + a.test(); + a.test2(); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/cfg5.rs b/gcc/testsuite/rust/execute/torture/cfg5.rs new file mode 100644 index 00000000000..581a29bb89d --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/cfg5.rs @@ -0,0 +1,13 @@ +// { dg-additional-options "-w -frust-cfg=A" } + +fn main() -> i32 { + let mut a = 0; + + #[cfg(A)] + a = 3; + + #[cfg(B)] + a = 40; + + a - 3 +} diff --git a/gcc/testsuite/rust/execute/torture/coercion1.rs b/gcc/testsuite/rust/execute/torture/coercion1.rs new file mode 100644 index 00000000000..2cdb9bbca38 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/coercion1.rs @@ -0,0 +1,41 @@ +/* { dg-output "123\n123\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +struct Foo(i32); +trait Bar { + fn baz(&self); +} + +impl Bar for Foo { + fn baz(&self) { + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, self.0); + } + } +} + +fn static_dispatch(t: &T) { + t.baz(); +} + +fn dynamic_dispatch(t: &dyn Bar) { + t.baz(); +} + +fn main() -> i32 { + let a; + a = Foo(123); + static_dispatch(&a); + + let b: &dyn Bar; + b = &a; + dynamic_dispatch(b); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/coercion2.rs b/gcc/testsuite/rust/execute/torture/coercion2.rs new file mode 100644 index 00000000000..12dd68ff5f7 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/coercion2.rs @@ -0,0 +1,39 @@ +/* { dg-output "123\n123\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +struct Foo(i32); +trait Bar { + fn baz(&self); +} + +impl Bar for Foo { + fn baz(&self) { + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, self.0); + } + } +} + +fn static_dispatch(t: &T) { + t.baz(); +} + +fn dynamic_dispatch(t: &dyn Bar) { + t.baz(); +} + +fn main() -> i32 { + let a; + a = &Foo(123); + + static_dispatch(a); + dynamic_dispatch(a); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/const_fold1.rs b/gcc/testsuite/rust/execute/torture/const_fold1.rs new file mode 100644 index 00000000000..3cd6c0c77b5 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/const_fold1.rs @@ -0,0 +1,13 @@ +// { dg-additional-options "-w" } +const fn const_fn() -> usize { + 4 +} + +const FN_TEST: usize = const_fn(); + +const TEST: usize = 2 + FN_TEST; + +fn main() -> i32 { + let a: [_; 12] = [5; TEST * 2]; + a[6] - 5 +} diff --git a/gcc/testsuite/rust/execute/torture/const_fold2.rs b/gcc/testsuite/rust/execute/torture/const_fold2.rs new file mode 100644 index 00000000000..c525648fe0b --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/const_fold2.rs @@ -0,0 +1,16 @@ +// { dg-additional-options "-w" } +const A: i32 = 1; +const B: i32 = { A + 2 }; + +const fn test() -> i32 { + B +} + +const C: i32 = { + const a: i32 = 4; + test() + a +}; + +fn main() -> i32 { + C - 7 +} diff --git a/gcc/testsuite/rust/execute/torture/copy_nonoverlapping1.rs b/gcc/testsuite/rust/execute/torture/copy_nonoverlapping1.rs new file mode 100644 index 00000000000..2ae7a0869e3 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/copy_nonoverlapping1.rs @@ -0,0 +1,17 @@ +extern "rust-intrinsic" { + pub fn copy_nonoverlapping(src: *const T, dst: *mut T, count: usize); +} + +fn main() -> i32 { + let i = 15; + let mut i_copy = 16; + + let i = &i as *const i32; + let i_copy = &mut i_copy as *mut i32; + + unsafe { + copy_nonoverlapping(i, i_copy, 1); + + *i_copy - *i + } +} \ No newline at end of file diff --git a/gcc/testsuite/rust/execute/torture/empty_main.rs b/gcc/testsuite/rust/execute/torture/empty_main.rs new file mode 100644 index 00000000000..6442e1e4e83 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/empty_main.rs @@ -0,0 +1,3 @@ +fn main() -> i32 { + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/execute.exp b/gcc/testsuite/rust/execute/torture/execute.exp new file mode 100644 index 00000000000..6dfb6d2b446 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/execute.exp @@ -0,0 +1,33 @@ +# Copyright (C) 2021-2022 Free Software Foundation, Inc. + +# This program 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 of the License, or +# (at your option) any later version. +# +# This program 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 +# . + +# Execute tests, torture testing. + +# Load support procs. +load_lib rust-dg.exp + +# Initialize `dg'. +dg-init + +# Main loop. +set saved-dg-do-what-default ${dg-do-what-default} + +set dg-do-what-default "run" +gcc-dg-runtest [lsort [glob -nocomplain $srcdir/$subdir/*.rs]] "" "" +set dg-do-what-default ${saved-dg-do-what-default} + +# All done. +dg-finish diff --git a/gcc/testsuite/rust/execute/torture/exit_error.rs b/gcc/testsuite/rust/execute/torture/exit_error.rs new file mode 100644 index 00000000000..c3d0d9f2480 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/exit_error.rs @@ -0,0 +1,5 @@ +// { dg-xfail-run-if "" { *-*-* } } + +fn main() -> i32 { + 1 +} diff --git a/gcc/testsuite/rust/execute/torture/extern_mod4.rs b/gcc/testsuite/rust/execute/torture/extern_mod4.rs new file mode 100644 index 00000000000..99b6fb5c9ba --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/extern_mod4.rs @@ -0,0 +1,19 @@ +// { dg-additional-options "-w" } +// { dg-output "12" } +mod modules; + +extern "C" { + fn printf(s: *const i8, ...); +} + +fn main() -> i32 { + unsafe { + let fmt_s = "%d\n\0"; + let fmt_p = fmt_s as *const str; + let fmt_i8 = fmt_p as *const i8; + + printf(fmt_i8, modules::return_12()); + } + + return 0; +} diff --git a/gcc/testsuite/rust/execute/torture/func1.rs b/gcc/testsuite/rust/execute/torture/func1.rs new file mode 100644 index 00000000000..0a093d88587 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/func1.rs @@ -0,0 +1,5 @@ +fn main() -> i32 { + 1; + 2; + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/helloworld1.rs b/gcc/testsuite/rust/execute/torture/helloworld1.rs new file mode 100644 index 00000000000..d416efa33af --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/helloworld1.rs @@ -0,0 +1,15 @@ +/* { dg-output "Hello World" }*/ +extern "C" { + fn puts(s: *const i8); +} + +fn main() -> i32 { + unsafe { + let a = "Hello World"; + let b = a as *const str; + let c = b as *const i8; + + puts(c); + } + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/helloworld2.rs b/gcc/testsuite/rust/execute/torture/helloworld2.rs new file mode 100644 index 00000000000..cc05f3798fa --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/helloworld2.rs @@ -0,0 +1,15 @@ +/* { dg-output "Hello World 123\n" }*/ +extern "C" { + fn printf(s: *const i8, ...); +} + +fn main() -> i32 { + unsafe { + let a = "Hello World %i\n"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, 123); + } + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/include.txt b/gcc/testsuite/rust/execute/torture/include.txt new file mode 100644 index 00000000000..12c368778e1 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/include.txt @@ -0,0 +1 @@ +hello, include! diff --git a/gcc/testsuite/rust/execute/torture/index1.rs b/gcc/testsuite/rust/execute/torture/index1.rs new file mode 100644 index 00000000000..4682978bdd0 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/index1.rs @@ -0,0 +1,28 @@ +// { dg-additional-options "-w" } +#[lang = "index"] +trait Index { + type Output; + + fn index(&self, index: Idx) -> &Self::Output; +} + +struct Foo(i32, i32); +impl Index for Foo { + type Output = i32; + + fn index(&self, index: isize) -> &i32 { + if index == 0 { + &self.0 + } else { + &self.1 + } + } +} + +fn main() -> i32 { + let a = Foo(1, 2); + let b = a[0]; + let c = a[1]; + + c - b - 1 +} diff --git a/gcc/testsuite/rust/execute/torture/issue-1120.rs b/gcc/testsuite/rust/execute/torture/issue-1120.rs new file mode 100644 index 00000000000..242c94b5cb6 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/issue-1120.rs @@ -0,0 +1,123 @@ +// { dg-additional-options "-w" } +extern "rust-intrinsic" { + #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")] + pub fn offset(dst: *const T, offset: isize) -> *const T; +} + +struct FatPtr { + data: *const T, + len: usize, +} + +pub union Repr { + rust: *const [T], + rust_mut: *mut [T], + raw: FatPtr, +} + +pub enum Option { + None, + Some(T), +} + +#[lang = "Range"] +pub struct Range { + pub start: Idx, + pub end: Idx, +} + +#[lang = "const_slice_ptr"] +impl *const [T] { + pub const fn len(self) -> usize { + unsafe { Repr { rust: self }.raw.len } + } + + pub const fn as_ptr(self) -> *const T { + self as *const T + } +} + +#[lang = "const_ptr"] +impl *const T { + pub const unsafe fn offset(self, count: isize) -> *const T { + unsafe { offset(self, count) } + } + + pub const unsafe fn add(self, count: usize) -> Self { + unsafe { self.offset(count as isize) } + } + + pub const fn as_ptr(self) -> *const T { + self as *const T + } +} + +const fn slice_from_raw_parts(data: *const T, len: usize) -> *const [T] { + unsafe { + Repr { + raw: FatPtr { data, len }, + } + .rust + } +} + +#[lang = "index"] +trait Index { + type Output; + + fn index(&self, index: Idx) -> &Self::Output; +} + +pub unsafe trait SliceIndex { + type Output; + + fn get(self, slice: &T) -> Option<&Self::Output>; + + unsafe fn get_unchecked(self, slice: *const T) -> *const Self::Output; + + fn index(self, slice: &T) -> &Self::Output; +} + +unsafe impl SliceIndex<[T]> for Range { + type Output = [T]; + + fn get(self, slice: &[T]) -> Option<&[T]> { + if self.start > self.end + /* || self.end > slice.len() */ + { + Option::None + } else { + unsafe { Option::Some(&*self.get_unchecked(slice)) } + } + } + + 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) } + } +} + +impl Index for [T] +where + I: SliceIndex<[T]>, +{ + type Output = I::Output; + + fn index(&self, index: I) -> &I::Output { + index.index(self) + } +} + +fn main() -> i32 { + let a = [1, 2, 3, 4, 5]; + let b = &a[1..3]; + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/issue-1133.rs b/gcc/testsuite/rust/execute/torture/issue-1133.rs new file mode 100644 index 00000000000..f2080a6e072 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/issue-1133.rs @@ -0,0 +1,146 @@ +// { dg-additional-options "-w" } +extern "rust-intrinsic" { + #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")] + pub fn offset(dst: *const T, offset: isize) -> *const T; +} + +struct FatPtr { + data: *const T, + len: usize, +} + +pub union Repr { + rust: *const [T], + rust_mut: *mut [T], + raw: FatPtr, +} + +pub enum Option { + None, + Some(T), +} + +#[lang = "Range"] +pub struct Range { + pub start: Idx, + pub end: Idx, +} + +#[lang = "const_slice_ptr"] +impl *const [T] { + pub const fn len(self) -> usize { + unsafe { Repr { rust: self }.raw.len } + } + + pub const fn as_ptr(self) -> *const T { + self as *const T + } +} + +#[lang = "const_ptr"] +impl *const T { + pub const unsafe fn offset(self, count: isize) -> *const T { + unsafe { offset(self, count) } + } + + pub const unsafe fn add(self, count: usize) -> Self { + unsafe { self.offset(count as isize) } + } + + pub const fn as_ptr(self) -> *const T { + self as *const T + } +} + +const fn slice_from_raw_parts(data: *const T, len: usize) -> *const [T] { + unsafe { + Repr { + raw: FatPtr { data, len }, + } + .rust + } +} + +#[lang = "index"] +trait Index { + type Output; + + fn index(&self, index: Idx) -> &Self::Output; +} + +pub unsafe trait SliceIndex { + type Output; + + fn get(self, slice: &T) -> Option<&Self::Output>; + + unsafe fn get_unchecked(self, slice: *const T) -> *const Self::Output; + + fn index(self, slice: &T) -> &Self::Output; +} + +unsafe impl SliceIndex<[T]> for usize { + type Output = T; + + fn get(self, slice: &[T]) -> Option<&T> { + unsafe { Option::Some(&*self.get_unchecked(slice)) } + } + + unsafe fn get_unchecked(self, slice: *const [T]) -> *const T { + // SAFETY: the caller guarantees that `slice` is not dangling, so it + // cannot be longer than `isize::MAX`. They also guarantee that + // `self` is in bounds of `slice` so `self` cannot overflow an `isize`, + // so the call to `add` is safe. + unsafe { slice.as_ptr().add(self) } + } + + fn index(self, slice: &[T]) -> &T { + // N.B., use intrinsic indexing + // &(*slice)[self] + unsafe { &*self.get_unchecked(slice) } + } +} + +unsafe impl SliceIndex<[T]> for Range { + type Output = [T]; + + fn get(self, slice: &[T]) -> Option<&[T]> { + if self.start > self.end + /* || self.end > slice.len() */ + { + Option::None + } else { + unsafe { Option::Some(&*self.get_unchecked(slice)) } + } + } + + 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) } + } +} + +impl Index for [T] +where + I: SliceIndex<[T]>, +{ + type Output = I::Output; + + fn index(&self, index: I) -> &I::Output { + index.index(self) + } +} + +fn main() -> i32 { + let a = [1, 2, 3, 4, 5]; + let b = &a[1..3]; + let c = b[1]; + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/issue-1198.rs b/gcc/testsuite/rust/execute/torture/issue-1198.rs new file mode 100644 index 00000000000..fce44ad1994 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/issue-1198.rs @@ -0,0 +1,75 @@ +/* { dg-output "foo_deref\nimm_deref\n123\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +#[lang = "deref"] +pub trait Deref { + type Target; + + fn deref(&self) -> &Self::Target; +} + +impl Deref for &T { + type Target = T; + + fn deref(&self) -> &T { + unsafe { + let a = "imm_deref\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + *self + } +} + +impl Deref for &mut T { + type Target = T; + + fn deref(&self) -> &T { + unsafe { + let a = "mut_deref\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + *self + } +} + +struct Foo(T); +impl Deref for Foo { + type Target = T; + + fn deref(&self) -> &Self::Target { + unsafe { + let a = "foo_deref\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + &self.0 + } +} + +fn main() -> i32 { + let foo: Foo = Foo(123); + let bar: &i32 = &foo; + + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, *bar); + } + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/issue-1231.rs b/gcc/testsuite/rust/execute/torture/issue-1231.rs new file mode 100644 index 00000000000..970e86f917a --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/issue-1231.rs @@ -0,0 +1,36 @@ +// { dg-additional-options "-w" } +// { dg-output "outer\ninner\n" } +extern "C" { + fn printf(s: *const i8, ...); +} + +fn machin() { + unsafe { + let a = "outer\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, 123); + } +} + +fn bidule() { + fn machin() { + unsafe { + let a = "inner\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, 123); + } + } + + self::machin(); + machin(); +} + +fn main() -> i32 { + bidule(); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/issue-1232.rs b/gcc/testsuite/rust/execute/torture/issue-1232.rs new file mode 100644 index 00000000000..c56d5c18695 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/issue-1232.rs @@ -0,0 +1,159 @@ +// { dg-additional-options "-w" } +// { dg-output "slice_access=3\n" } +extern "rust-intrinsic" { + #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")] + fn offset(dst: *const T, offset: isize) -> *const T; +} + +extern "C" { + fn printf(s: *const i8, ...); +} + +struct FatPtr { + data: *const T, + len: usize, +} + +pub union Repr { + rust: *const [T], + rust_mut: *mut [T], + raw: FatPtr, +} + +pub enum Option { + None, + Some(T), +} + +#[lang = "Range"] +pub struct Range { + pub start: Idx, + pub end: Idx, +} + +#[lang = "const_slice_ptr"] +impl *const [T] { + pub const fn len(self) -> usize { + unsafe { Repr { rust: self }.raw.len } + } + + pub const fn as_ptr(self) -> *const T { + self as *const T + } +} + +#[lang = "const_ptr"] +impl *const T { + pub const unsafe fn offset(self, count: isize) -> *const T { + unsafe { offset(self, count) } + } + + pub const unsafe fn add(self, count: usize) -> Self { + unsafe { self.offset(count as isize) } + } + + pub const fn as_ptr(self) -> *const T { + self as *const T + } +} + +const fn slice_from_raw_parts(data: *const T, len: usize) -> *const [T] { + unsafe { + Repr { + raw: FatPtr { data, len }, + } + .rust + } +} + +#[lang = "index"] +trait Index { + type Output; + + fn index(&self, index: Idx) -> &Self::Output; +} + +pub unsafe trait SliceIndex { + type Output; + + fn get(self, slice: &T) -> Option<&Self::Output>; + + unsafe fn get_unchecked(self, slice: *const T) -> *const Self::Output; + + fn index(self, slice: &T) -> &Self::Output; +} + +unsafe impl SliceIndex<[T]> for usize { + type Output = T; + + fn get(self, slice: &[T]) -> Option<&T> { + unsafe { Option::Some(&*self.get_unchecked(slice)) } + } + + unsafe fn get_unchecked(self, slice: *const [T]) -> *const T { + // SAFETY: the caller guarantees that `slice` is not dangling, so it + // cannot be longer than `isize::MAX`. They also guarantee that + // `self` is in bounds of `slice` so `self` cannot overflow an `isize`, + // so the call to `add` is safe. + unsafe { slice.as_ptr().add(self) } + } + + fn index(self, slice: &[T]) -> &T { + // N.B., use intrinsic indexing + // &(*slice)[self] + unsafe { &*self.get_unchecked(slice) } + } +} + +unsafe impl SliceIndex<[T]> for Range { + type Output = [T]; + + fn get(self, slice: &[T]) -> Option<&[T]> { + if self.start > self.end + /* || self.end > slice.len() */ + { + Option::None + } else { + unsafe { Option::Some(&*self.get_unchecked(slice)) } + } + } + + 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) } + } +} + +impl Index for [T] +where + I: SliceIndex<[T]>, +{ + type Output = I::Output; + + fn index(&self, index: I) -> &I::Output { + index.index(self) + } +} + +fn main() -> i32 { + let array = [1, 2, 3, 4, 5]; + let slice = &array[1..3]; + let slice_access = slice[1]; + + unsafe { + let a = "slice_access=%i\n"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, slice_access); + } + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/issue-1249.rs b/gcc/testsuite/rust/execute/torture/issue-1249.rs new file mode 100644 index 00000000000..072204ea877 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/issue-1249.rs @@ -0,0 +1,39 @@ +// { dg-options "-w" } +// { dg-output "1\n2\n" } + +extern "C" { + fn printf(s: *const i8, ...); +} + +trait T { + fn foo(&self); +} + +impl dyn T { + fn bar(&self) { + unsafe { + let a = "1\n\0"; + let b = a as *const str; + let c = b as *const i8; + printf(c); + } + self.foo() + } +} + +struct S; +impl T for S { + fn foo(&self) { + unsafe { + let a = "2\n\0"; + let b = a as *const str; + let c = b as *const i8; + printf(c); + } + } +} + +pub fn main() -> i32 { + ::bar(&S); + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/issue-1436.rs b/gcc/testsuite/rust/execute/torture/issue-1436.rs new file mode 100644 index 00000000000..5c079a61f07 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/issue-1436.rs @@ -0,0 +1,172 @@ +// { dg-options "-w" } +// { dg-output "" } +mod intrinsics { + extern "rust-intrinsic" { + #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")] + pub fn offset(ptr: *const T, count: isize) -> *const T; + } +} + +mod mem { + extern "rust-intrinsic" { + fn size_of() -> usize; + } +} + +extern "C" { + fn printf(s: *const i8, ...); +} + +struct FatPtr { + data: *const T, + len: usize, +} + +pub union Repr { + rust: *const [T], + rust_mut: *mut [T], + raw: FatPtr, +} + +pub enum Option { + None, + Some(T), +} + +#[lang = "Range"] +pub struct Range { + pub start: Idx, + pub end: Idx, +} + +#[lang = "const_slice_ptr"] +impl *const [T] { + pub const fn len(self) -> usize { + unsafe { Repr { rust: self }.raw.len } + } + + pub const fn as_ptr(self) -> *const T { + self as *const T + } +} + +#[lang = "const_ptr"] +impl *const T { + pub const unsafe fn offset(self, count: isize) -> *const T { + unsafe { intrinsics::offset(self, count) } + } + + pub const unsafe fn add(self, count: usize) -> Self { + unsafe { self.offset(count as isize) } + } + + pub const fn as_ptr(self) -> *const T { + self as *const T + } +} + +const fn slice_from_raw_parts(data: *const T, len: usize) -> *const [T] { + unsafe { + Repr { + raw: FatPtr { data, len }, + } + .rust + } +} + +#[lang = "index"] +trait Index { + type Output; + + fn index(&self, index: Idx) -> &Self::Output; +} + +impl [T] { + pub const fn is_empty(&self) -> bool { + self.len() == 0 + } + + pub const fn len(&self) -> usize { + unsafe { Repr { rust: self }.raw.len } + } +} + +pub unsafe trait SliceIndex { + type Output; + + fn get(self, slice: &T) -> Option<&Self::Output>; + + unsafe fn get_unchecked(self, slice: *const T) -> *const Self::Output; + + fn index(self, slice: &T) -> &Self::Output; +} + +unsafe impl SliceIndex<[T]> for usize { + type Output = T; + + fn get(self, slice: &[T]) -> Option<&T> { + unsafe { Option::Some(&*self.get_unchecked(slice)) } + } + + unsafe fn get_unchecked(self, slice: *const [T]) -> *const T { + // SAFETY: the caller guarantees that `slice` is not dangling, so it + // cannot be longer than `isize::MAX`. They also guarantee that + // `self` is in bounds of `slice` so `self` cannot overflow an `isize`, + // so the call to `add` is safe. + unsafe { slice.as_ptr().add(self) } + } + + fn index(self, slice: &[T]) -> &T { + unsafe { &*self.get_unchecked(slice) } + } +} + +unsafe impl SliceIndex<[T]> for Range { + type Output = [T]; + + fn get(self, slice: &[T]) -> Option<&[T]> { + if self.start > self.end || self.end > slice.len() { + Option::None + } else { + unsafe { Option::Some(&*self.get_unchecked(slice)) } + } + } + + 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) } + } +} + +impl Index for [T] +where + I: SliceIndex<[T]>, +{ + type Output = I::Output; + + fn index(&self, index: I) -> &I::Output { + unsafe { + let a = "slice-index\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + index.index(self) + } +} + +fn main() -> i32 { + let a = [1, 2, 3, 4, 5]; + let b = a[1]; + + b - 2 +} diff --git a/gcc/testsuite/rust/execute/torture/issue-1496.rs b/gcc/testsuite/rust/execute/torture/issue-1496.rs new file mode 100644 index 00000000000..9f08b2ae98a --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/issue-1496.rs @@ -0,0 +1,75 @@ +/* { dg-output "foo_deref\nimm_deref\n123\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +#[lang = "deref"] +pub trait Deref { + type Target; + + fn deref(&self) -> &Self::Target; +} + +impl Deref for &T { + type Target = T; + + fn deref(&self) -> &T { + unsafe { + let a = "imm_deref\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + *self + } +} + +impl Deref for &mut T { + type Target = T; + + fn deref(&self) -> &T { + unsafe { + let a = "mut_deref\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + *self + } +} + +struct Foo(T); +impl Deref for Foo { + type Target = T; + + fn deref(&self) -> &Self::Target { + unsafe { + let a = "foo_deref\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + &self.0 + } +} + +fn main() -> i32 { + let foo = Foo(123); + let bar = &foo as &i32; + + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, *bar); + } + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/issue-647.rs b/gcc/testsuite/rust/execute/torture/issue-647.rs new file mode 100644 index 00000000000..3f427ccb785 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/issue-647.rs @@ -0,0 +1,33 @@ +/* { dg-output "Hello World 123\n" }*/ +extern "C" { + fn printf(s: *const i8, ...); +} + +struct Foo(T); + +struct Bar { + a: Foo, + b: bool, + // { dg-warning "field is never read" "" { target *-*-* } .-1 } +} + +fn test(a: Bar) -> Foo { + a.a +} + +fn main() -> i32 { + let a: Bar = Bar:: { + a: Foo::(123), + b: true, + }; + let result: Foo = test(a); + + unsafe { + let a = "Hello World %i\n"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, result.0); + } + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/issue-845.rs b/gcc/testsuite/rust/execute/torture/issue-845.rs new file mode 100644 index 00000000000..4c689e3b6c8 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/issue-845.rs @@ -0,0 +1,47 @@ +// { dg-output "Foo::bar\n" } +// { dg-additional-options "-w" } +extern "C" { + fn printf(s: *const i8, ...); +} + +struct Foo {} + +trait Bar { + fn bar(&self) { + unsafe { + let _a = "Bar::bar\n\0"; + let _b = _a as *const str; + let _c = _b as *const i8; + printf(_c); + } + } +} + +impl Foo { + fn bar(&self) { + unsafe { + let _a = "Foo::bar\n\0"; + let _b = _a as *const str; + let _c = _b as *const i8; + printf(_c); + } + } +} + +impl Bar for Foo { + fn bar(&self) { + unsafe { + let _a = "::bar\n\0"; + let _b = _a as *const str; + let _c = _b as *const i8; + printf(_c); + } + } +} + +pub fn main() -> i32 { + let mut f = Foo {}; + f.bar(); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/issue-851.rs b/gcc/testsuite/rust/execute/torture/issue-851.rs new file mode 100644 index 00000000000..3881c7a2ada --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/issue-851.rs @@ -0,0 +1,35 @@ +/* { dg-output "Result: 123\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +enum Foo { + A, + B(T), +} + +fn inspect(a: Foo) { + match a { + Foo::A => unsafe { + let a = "A\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + }, + Foo::B(x) => unsafe { + let a = "Result: %i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, x); + }, + } +} + +fn main() -> i32 { + let a = Foo::B(123); + inspect(a); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/issue-858.rs b/gcc/testsuite/rust/execute/torture/issue-858.rs new file mode 100644 index 00000000000..5a43f3e1b1a --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/issue-858.rs @@ -0,0 +1,32 @@ +/* { dg-output "Result: 123\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +enum Foo { + A, + B(T), +} + +fn main() -> i32 { + let result = Foo::B(123); + + match result { + Foo::A => unsafe { + let a = "A\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + }, + Foo::B(x) => unsafe { + let a = "Result: %i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, x); + }, + } + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/issue-976.rs b/gcc/testsuite/rust/execute/torture/issue-976.rs new file mode 100644 index 00000000000..42cf596fb7d --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/issue-976.rs @@ -0,0 +1,14 @@ +/* { dg-output "hi" } */ +fn main() -> i32 { + { + extern "C" { + fn puts(s: *const i8); + } + + unsafe { + puts("hi\0" as *const str as *const i8); + } + } + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/issue-995.rs b/gcc/testsuite/rust/execute/torture/issue-995.rs new file mode 100644 index 00000000000..42570e33f74 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/issue-995.rs @@ -0,0 +1,9 @@ +struct Pattern(i32); + +fn pattern_as_arg(Pattern(value): Pattern) -> i32 { + value +} + +fn main() -> i32 { + pattern_as_arg(Pattern(15)) - 15 +} diff --git a/gcc/testsuite/rust/execute/torture/macros1.rs b/gcc/testsuite/rust/execute/torture/macros1.rs new file mode 100644 index 00000000000..652d2d8fe5b --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros1.rs @@ -0,0 +1,13 @@ +macro_rules! add { + ($a:expr,$b:expr) => { + $a + $b + }; +} + +fn test() -> i32 { + add!(1 + 2, 3) +} + +fn main() -> i32 { + test() - 6 +} diff --git a/gcc/testsuite/rust/execute/torture/macros10.rs b/gcc/testsuite/rust/execute/torture/macros10.rs new file mode 100644 index 00000000000..155a440ee04 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros10.rs @@ -0,0 +1,22 @@ +// { dg-output "18\n" } +extern "C" { + fn printf(s: *const i8, ...); +} + +fn print_int(value: i32) { + let s = "%d\n\0" as *const str as *const i8; + unsafe { + printf(s, value); + } +} + +macro_rules! add_exprs { + ($($e:expr)*) => (0 $(+ $e)*) +} + +fn main() -> i32 { + // 1 + 2 + 15 => 18 + print_int(add_exprs!(1 2 15)); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/macros11.rs b/gcc/testsuite/rust/execute/torture/macros11.rs new file mode 100644 index 00000000000..5bde97d3dd4 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros11.rs @@ -0,0 +1,25 @@ +// { dg-output "2" } +extern "C" { + fn printf(s: *const i8, ...); +} + +fn print_int(value: i32) { + let s = "%d\n\0"; + let s_p = s as *const str; + let c_p = s_p as *const i8; + unsafe { + printf(c_p, value); + } +} + +macro_rules! add_exprs { + ($($e:expr)?) => (0 $(+ $e)?) +} + +fn main() -> i32 { + // 2 + let a = add_exprs!(2); + print_int(a); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/macros12.rs b/gcc/testsuite/rust/execute/torture/macros12.rs new file mode 100644 index 00000000000..d310dff9ba8 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros12.rs @@ -0,0 +1,22 @@ +// { dg-output "0\n" } +extern "C" { + fn printf(s: *const i8, ...); +} + +fn print_int(value: i32) { + let s = "%d\n\0" as *const str as *const i8; + unsafe { + printf(s, value); + } +} + +macro_rules! add_exprs { + ($($e:expr)?) => (0 $(+ $e)?) +} + +fn main() -> i32 { + // 0 + print_int(add_exprs!()); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/macros13.rs b/gcc/testsuite/rust/execute/torture/macros13.rs new file mode 100644 index 00000000000..afb20264625 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros13.rs @@ -0,0 +1,22 @@ +// { dg-output "18\n" } +extern "C" { + fn printf(s: *const i8, ...); +} + +fn print_int(value: i32) { + let s = "%d\n\0" as *const str as *const i8; + unsafe { + printf(s, value); + } +} + +macro_rules! add_exprs { + ($($e:expr)+) => (0 $(+ $e)+) +} + +fn main() -> i32 { + // 1 + 2 + 15 => 18 + print_int(add_exprs!(1 2 15)); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/macros14.rs b/gcc/testsuite/rust/execute/torture/macros14.rs new file mode 100644 index 00000000000..00656546d4c --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros14.rs @@ -0,0 +1,22 @@ +// { dg-output "15\n" } +extern "C" { + fn printf(s: *const i8, ...); +} + +fn print_int(value: i32) { + let s = "%d\n\0" as *const str as *const i8; + unsafe { + printf(s, value); + } +} + +macro_rules! add_exprs { + ($($e:expr)*) => (15 $(+ $e)*) +} + +fn main() -> i32 { + // 15 + print_int(add_exprs!()); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/macros16.rs b/gcc/testsuite/rust/execute/torture/macros16.rs new file mode 100644 index 00000000000..47ab2411c0d --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros16.rs @@ -0,0 +1,14 @@ +macro_rules! add { + ($e:literal) => { + 0 + $e + }; + ($e:literal $($es:literal)*) => { + $e + add!($($es)*) + }; +} + +fn main() -> i32 { + let a = add!(1 2 3 10); // 16 + + a - 16 +} diff --git a/gcc/testsuite/rust/execute/torture/macros17.rs b/gcc/testsuite/rust/execute/torture/macros17.rs new file mode 100644 index 00000000000..390352ec47f --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros17.rs @@ -0,0 +1,17 @@ +macro_rules! two { + (2) => { + 3 + }; +} + +macro_rules! one { + (1) => {{ + two!(2) + }}; +} + +fn main() -> i32 { + let a = one!(1); + + a - 3 +} diff --git a/gcc/testsuite/rust/execute/torture/macros18.rs b/gcc/testsuite/rust/execute/torture/macros18.rs new file mode 100644 index 00000000000..61df17e9da5 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros18.rs @@ -0,0 +1,14 @@ +macro_rules! add { + ($e:literal) => { + 0 + $e + }; + ($e:literal $($es:literal)*) => { + $e + add!($($es)*) + }; +} + +fn main() -> i32 { + let a = add!(3 4); // 7 + + a - 7 +} diff --git a/gcc/testsuite/rust/execute/torture/macros19.rs b/gcc/testsuite/rust/execute/torture/macros19.rs new file mode 100644 index 00000000000..4732545410e --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros19.rs @@ -0,0 +1,14 @@ +macro_rules! add { + ($e:expr, $($es:expr),*) => { + $e + add!($($es),*) + }; + ($e:expr) => { + $e + }; +} + +fn main() -> i32 { + let a = add!(15, 2, 9); // 26 + + a - 26 +} diff --git a/gcc/testsuite/rust/execute/torture/macros2.rs b/gcc/testsuite/rust/execute/torture/macros2.rs new file mode 100644 index 00000000000..ba5098710ea --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros2.rs @@ -0,0 +1,40 @@ +// { dg-output "arg\narg\narg\n" } +extern "C" { + fn printf(s: *const i8, ...); +} + +fn f() { + unsafe { + let r_s = "arg\n\0"; + let s_p = r_s as *const str; + let c_p = s_p as *const i8; + + printf(c_p); + } +} + +macro_rules! kw0 { + (keyword) => { + f(); + }; +} + +macro_rules! kw1 { + (fn) => { + f(); + }; +} + +macro_rules! kw2 { + (kw0 kw1 kw3) => { + f(); + }; +} + +fn main() -> i32 { + kw0!(keyword); + kw1!(fn); + kw2!(kw0 kw1 kw3); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/macros20.rs b/gcc/testsuite/rust/execute/torture/macros20.rs new file mode 100644 index 00000000000..97317a0879e --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros20.rs @@ -0,0 +1,14 @@ +macro_rules! add { + ($e:expr , $($es:expr) , *) => { + $e + add!($($es) , *) + }; + ($e:expr) => { + $e + }; +} + +fn main() -> i32 { + let a = add!(15, 2, 9); // 26 + + a - 26 +} diff --git a/gcc/testsuite/rust/execute/torture/macros21.rs b/gcc/testsuite/rust/execute/torture/macros21.rs new file mode 100644 index 00000000000..2508be1a6fd --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros21.rs @@ -0,0 +1,15 @@ +macro_rules! add_parens { + ($($rep:ident ( ) )*) => { + { 0 $(+ $rep ( ))* } + }; +} + +fn f() -> i32 { + 1 +} + +fn main() -> i32 { + let a = add_parens!(f() f() f()); + + a - 3 +} diff --git a/gcc/testsuite/rust/execute/torture/macros22.rs b/gcc/testsuite/rust/execute/torture/macros22.rs new file mode 100644 index 00000000000..3f291ace98e --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros22.rs @@ -0,0 +1,27 @@ +// { dg-output "1\n2\nNaN\n3\n" } + +macro_rules! print_num { + ($l:literal) => {{ + unsafe { + printf("%d\n\0" as *const str as *const i8, $l); + } + }}; +} + +extern "C" { + fn printf(s: *const i8, ...); +} + +// Check to make sure that expanding macros does not break the flow of calls +fn main() -> i32 { + print_num!(1); + print_num!(2); + + unsafe { + printf("NaN\n\0" as *const str as *const i8); + } + + print_num!(3); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/macros23.rs b/gcc/testsuite/rust/execute/torture/macros23.rs new file mode 100644 index 00000000000..846352d0487 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros23.rs @@ -0,0 +1,19 @@ +trait Valuable { + const VALUE: i32; +} + +struct Something; + +macro_rules! implement { + () => { + const VALUE: i32 = 18; + }; +} + +impl Valuable for Something { + implement!(); +} + +fn main() -> i32 { + Something::VALUE - 18 +} diff --git a/gcc/testsuite/rust/execute/torture/macros24.rs b/gcc/testsuite/rust/execute/torture/macros24.rs new file mode 100644 index 00000000000..f838a83af66 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros24.rs @@ -0,0 +1,9 @@ +macro_rules! repeat { + ( $( $i:literal ),* ; $( $j:literal ),* ) => (( $( ($i,$j) ),* )) +} + +fn main() -> i32 { + let t = repeat!(1, 1; 2, 2); + + t.0 .0 + t.0 .1 + t.1 .0 + t.1 .1 - 6 +} diff --git a/gcc/testsuite/rust/execute/torture/macros25.rs b/gcc/testsuite/rust/execute/torture/macros25.rs new file mode 100644 index 00000000000..c2658721bdf --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros25.rs @@ -0,0 +1,13 @@ +macro_rules! t { + ($t:tt) => { + $t + }; +} + +fn frob() -> i32 { + t!(15) + t!((14)) +} + +fn main() -> i32 { + frob() - 29 +} diff --git a/gcc/testsuite/rust/execute/torture/macros26.rs b/gcc/testsuite/rust/execute/torture/macros26.rs new file mode 100644 index 00000000000..30f0beef0d9 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros26.rs @@ -0,0 +1,12 @@ +macro_rules! count_tt { + ($t:tt) => { 1 }; + ($t:tt $($ts:tt)*) => { 1 + count_tt!($($ts)*) }; +} + +fn main() -> i32 { + let count = count_tt!(1 2 let a = 15) + count_tt!(1 2 (let a = 15)); + // ^ ^ ^^^ ^ ^ ^^ ^ ^ ^^^^^^^^^^^^ + // 6 token-trees 3 token-trees + + count - 9 +} diff --git a/gcc/testsuite/rust/execute/torture/macros27.rs b/gcc/testsuite/rust/execute/torture/macros27.rs new file mode 100644 index 00000000000..d515bb278a0 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros27.rs @@ -0,0 +1,24 @@ +// { dg-additional-options "-frust-cfg=A" } + +macro_rules! attr { + (#[$attr:meta] $s:stmt) => { + #[$attr] + $s; + }; +} + +fn main() -> i32 { + let mut a = 0; + + attr! { + #[cfg(A)] + a = 3 + }; + + attr! { + #[cfg(B)] + a = 40 + }; + + a - 3 +} diff --git a/gcc/testsuite/rust/execute/torture/macros28.rs b/gcc/testsuite/rust/execute/torture/macros28.rs new file mode 100644 index 00000000000..b011f924149 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros28.rs @@ -0,0 +1,13 @@ +macro_rules! t { + () => { + i32 + }; +} + +fn id(arg: T) -> T { + arg +} + +fn main() -> i32 { + id::(15) - 15 +} diff --git a/gcc/testsuite/rust/execute/torture/macros29.rs b/gcc/testsuite/rust/execute/torture/macros29.rs new file mode 100644 index 00000000000..306979b9b5b --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros29.rs @@ -0,0 +1,24 @@ +// { dg-output "1\n" } +#[rustc_builtin_macro] +macro_rules! concat { + () => {{}}; +} + +extern "C" { + fn printf(fmt: *const i8, ...); +} + +fn print(s: u32) { + unsafe { + printf("%u\n\0" as *const str as *const i8, s); + } +} + +fn main() -> i32 { + let res = concat!("test2") == "test3"; + if !res { + print(1); + } + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/macros3.rs b/gcc/testsuite/rust/execute/torture/macros3.rs new file mode 100644 index 00000000000..00f6d253f50 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros3.rs @@ -0,0 +1,61 @@ +// { dg-output "invok\ninvok\ninvok\ninvok\ninvok\n" } +extern "C" { + fn printf(s: *const i8, ...); +} + +fn f() { + unsafe { + let r_s = "invok\n\0"; + let s_p = r_s as *const str; + let c_p = s_p as *const i8; + + printf(c_p); + } +} + +macro_rules! invocation0 { + (valid) => { + f(); + }; + () => {}; +} + +macro_rules! invocation1 { + (valid) => {}; + () => { + f(); + }; +} + +macro_rules! invocation2 { + (valid) => { + f(); + }; + (invalid) => {}; +} + +macro_rules! invocation3 { + (this is a valid invocation) => { + f(); + }; + (not this one) => {}; +} + +macro_rules! invocation4 { + (fn f() {}) => { + f(); + }; + (not a keyword) => {}; +} + +fn main() -> i32 { + invocation0!(valid); + invocation1!(); + invocation2!(valid); + invocation3!(this is a valid invocation); + invocation4!( + fn f() {} + ); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/macros30.rs b/gcc/testsuite/rust/execute/torture/macros30.rs new file mode 100644 index 00000000000..ab36f5e78af --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros30.rs @@ -0,0 +1,25 @@ +// { dg-output "1\n" } +#[rustc_builtin_macro] +macro_rules! concat { + () => {{}}; +} + +extern "C" { + fn printf(fmt: *const i8, ...); +} + +fn print(s: u32) { + unsafe { + printf("%u\n\0" as *const str as *const i8, s); + } +} + +fn main() -> i32 { + let mut x = concat!("x"); + x = concat!("y"); + if x == "y" { + print(1); + } + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/macros31.rs b/gcc/testsuite/rust/execute/torture/macros31.rs new file mode 100644 index 00000000000..483f897a92b --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros31.rs @@ -0,0 +1,32 @@ +// { dg-additional-options "-w -frust-cfg=A" } +// { dg-output "A\nB\n" } +#[rustc_builtin_macro] +macro_rules! cfg { + () => {{}}; +} + +extern "C" { + fn printf(fmt: *const i8, ...); +} + +fn print(s: &str) { + unsafe { + printf( + "%s\n" as *const str as *const i8, + s as *const str as *const i8, + ); + } +} + +fn main() -> i32 { + let cfg = cfg!(A) || cfg!(B); + if cfg { + print("A"); + } + let cfg = cfg!(A) && cfg!(B); + if !cfg { + print("B"); + } + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/macros4.rs b/gcc/testsuite/rust/execute/torture/macros4.rs new file mode 100644 index 00000000000..3303bfa58aa --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros4.rs @@ -0,0 +1,15 @@ +macro_rules! add { + ($a:expr,$b:expr) => { + $a + $b + }; + ($a:expr) => { + $a + }; +} + +fn main() -> i32 { + let mut x = add!(1); + x += add!(2, 3); + + x - 6 +} diff --git a/gcc/testsuite/rust/execute/torture/macros5.rs b/gcc/testsuite/rust/execute/torture/macros5.rs new file mode 100644 index 00000000000..822665494a4 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros5.rs @@ -0,0 +1,13 @@ +macro_rules! add { + ($a:expr,$b:expr) => {{ + $a + $b + }}; +} + +fn test() -> i32 { + add!(1, 2) +} + +fn main() -> i32 { + test() - 3 +} diff --git a/gcc/testsuite/rust/execute/torture/macros6.rs b/gcc/testsuite/rust/execute/torture/macros6.rs new file mode 100644 index 00000000000..652a765d5a8 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros6.rs @@ -0,0 +1,12 @@ +macro_rules! Test { + ($a:ident, $b:ty) => { + struct $a($b); + }; +} + +Test!(Foo, i32); + +fn main() -> i32 { + let a = Foo(123); + a.0 - 123 +} diff --git a/gcc/testsuite/rust/execute/torture/macros7.rs b/gcc/testsuite/rust/execute/torture/macros7.rs new file mode 100644 index 00000000000..ed1f922f581 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros7.rs @@ -0,0 +1,28 @@ +// { dg-output "any\nany\nany\n" } +extern "C" { + fn printf(s: *const i8, ...); +} + +fn f() { + let r_s = "any\n\0"; + let s_p = r_s as *const str; + let c_p = s_p as *const i8; + + unsafe { + printf(c_p); + } +} + +macro_rules! any { + ($($a:expr)*) => { + f(); + }; +} + +fn main() -> i32 { + any!(); + any!(a + b); + any!(a + b 14 "gcc"); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/macros8.rs b/gcc/testsuite/rust/execute/torture/macros8.rs new file mode 100644 index 00000000000..a12aca4910e --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros8.rs @@ -0,0 +1,27 @@ +// { dg-output "zo1\nzo1\n" } +extern "C" { + fn printf(s: *const i8, ...); +} + +fn f() { + let r_s = "zo1\n\0"; + let s_p = r_s as *const str; + let c_p = s_p as *const i8; + + unsafe { + printf(c_p); + } +} + +macro_rules! zero_or_one { + ($($a:expr)?) => { + f(); + }; +} + +fn main() -> i32 { + zero_or_one!(); + zero_or_one!(f()); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/macros9.rs b/gcc/testsuite/rust/execute/torture/macros9.rs new file mode 100644 index 00000000000..0e3fd24e8a9 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/macros9.rs @@ -0,0 +1,28 @@ +// { dg-output "oom\noom\noom\n" } +extern "C" { + fn printf(s: *const i8, ...); +} + +fn f() { + let r_s = "oom\n\0"; + let s_p = r_s as *const str; + let c_p = s_p as *const i8; + + unsafe { + printf(c_p); + } +} + +macro_rules! one_or_more { + ($($a:expr)+) => { + f(); + }; +} + +fn main() -> i32 { + one_or_more!(f()); + one_or_more!(f() f()); + one_or_more!(f() f() 15 + 12); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/match1.rs b/gcc/testsuite/rust/execute/torture/match1.rs new file mode 100644 index 00000000000..e5af512f15d --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/match1.rs @@ -0,0 +1,58 @@ +// { dg-output "Foo::A\nFoo::B\nFoo::C x\nFoo::D 20 80\n" } +extern "C" { + fn printf(s: *const i8, ...); +} + +enum Foo { + A, + B, + C(char), + D { x: i32, y: i32 }, +} + +fn inspect(f: Foo) { + match f { + Foo::A => unsafe { + let a = "Foo::A\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + }, + Foo::B => unsafe { + let a = "Foo::B\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + }, + Foo::C(x) => unsafe { + let a = "Foo::C %c\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, x); + }, + Foo::D { x, y } => unsafe { + let a = "Foo::D %i %i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, x, y); + }, + } +} + +fn main() -> i32 { + let a = Foo::A; + let b = Foo::B; + let c = Foo::C('x'); + let d = Foo::D { x: 20, y: 80 }; + + inspect(a); + inspect(b); + inspect(c); + inspect(d); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/match2.rs b/gcc/testsuite/rust/execute/torture/match2.rs new file mode 100644 index 00000000000..02cedf29b3c --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/match2.rs @@ -0,0 +1,41 @@ +// { dg-output "123\n80\n" } +extern "C" { + fn printf(s: *const i8, ...); +} + +enum Foo { + C(i32), + D { x: i32, y: i32 }, +} + +fn inspect(f: Foo) -> i32 { + match f { + Foo::C(x) => x, + Foo::D { x, y } => y, + } +} + +fn main() -> i32 { + let a = Foo::C(123); + let b = Foo::D { x: 20, y: 80 }; + + let result = inspect(a); + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, result); + } + + let result = inspect(b); + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, result); + } + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/match3.rs b/gcc/testsuite/rust/execute/torture/match3.rs new file mode 100644 index 00000000000..8cded3044df --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/match3.rs @@ -0,0 +1,51 @@ +// { dg-output "Foo::A\nwildcard\nwildcard\nFoo::D 20 80\n" } +extern "C" { + fn printf(s: *const i8, ...); +} + +enum Foo { + A, + B, + C(char), + D { x: i32, y: i32 }, +} + +fn inspect(f: Foo) { + match f { + Foo::A => unsafe { + let a = "Foo::A\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + }, + Foo::D { x, y } => unsafe { + let a = "Foo::D %i %i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, x, y); + }, + _ => unsafe { + let a = "wildcard\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + }, + } +} + +fn main() -> i32 { + let a = Foo::A; + let b = Foo::B; + let c = Foo::C('x'); + let d = Foo::D { x: 20, y: 80 }; + + inspect(a); + inspect(b); + inspect(c); + inspect(d); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/match_bool1.rs b/gcc/testsuite/rust/execute/torture/match_bool1.rs new file mode 100644 index 00000000000..101dbb58571 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/match_bool1.rs @@ -0,0 +1,49 @@ +// { dg-output "182 is more than 100\n55 is less than 100\n" } + +extern "C" { + fn printf(s: *const i8, ...); +} + +fn foo(x: bool) -> i32 { + match x { + true => { + return 182; + } + false => { + return 55; + } + } +} + +fn bar(y: i32) { + match y < 100 { + true => { + let a = "%i is less than 100\n\0"; + let b = a as *const str; + let c = b as *const i8; + + unsafe { + printf(c, y); + } + } + _ => { + let a = "%i is more than 100\n\0"; + let b = a as *const str; + let c = b as *const i8; + + unsafe { + printf(c, y); + } + } + } +} + +fn main() -> i32 { + let a = foo(true); + let b = foo(false); + + bar(a); + bar(b); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/match_byte1.rs b/gcc/testsuite/rust/execute/torture/match_byte1.rs new file mode 100644 index 00000000000..3546cfb9d8b --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/match_byte1.rs @@ -0,0 +1,56 @@ +// { dg-output "a\nseven\nquote\nelse" } + +extern "C" { + fn printf(s: *const i8, ...); +} + +fn foo(x: u8) { + match x { + b'a' => { + let a = "a\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + } + + b'\x07' => { + let a = "seven\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + } + + b'\'' => { + let a = "quote\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + } + + _ => { + let a = "else\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + } + } +} + +fn main() -> i32 { + let x: u8 = 7; + + foo(b'a'); + foo(x); + foo(b'\''); + foo(b'\\'); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/match_char1.rs b/gcc/testsuite/rust/execute/torture/match_char1.rs new file mode 100644 index 00000000000..fa65876a907 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/match_char1.rs @@ -0,0 +1,56 @@ +// { dg-output "amazing\nwildcard\ncompiler\nproductivity\n" } + +extern "C" { + fn printf(s: *const i8, ...); +} + +fn foo(x: char) { + match x { + 'a' => { + let a = "amazing\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + } + + 'c' => { + let a = "compiler\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + } + + 'p' => { + let a = "productivity\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + } + + _ => { + let a = "wildcard\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + } + } +} + +fn main() -> i32 { + let p = 'p'; + + foo('a'); + foo('b'); + foo('c'); + foo(p); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/match_int1.rs b/gcc/testsuite/rust/execute/torture/match_int1.rs new file mode 100644 index 00000000000..209429added --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/match_int1.rs @@ -0,0 +1,109 @@ +// { dg-output "other!\nother!\nother!\nfifteen!\nfifteen!\nother!\nother!\nfifteen!\n" } + +extern "C" { + fn printf(s: *const i8, ...); +} + +fn foo_i32(x: i32) { + match x { + 15 => { + let a = "fifteen!\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + } + + _ => { + let a = "other!\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + } + } +} + +fn foo_isize(x: isize) { + match x { + 15 => { + let a = "fifteen!\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + } + + _ => { + let a = "other!\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + } + } +} + +fn foo_u32(x: u32) { + match x { + 15 => { + let a = "fifteen!\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + } + + _ => { + let a = "other!\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + } + } +} + +fn foo_usize(x: usize) { + match x { + 15 => { + let a = "fifteen!\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + } + + _ => { + let a = "other!\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + } + } +} + +fn main() -> i32 { + let x = -2; + foo_i32(x); + foo_i32(334); + foo_isize(-4768); + foo_isize(15); + + let y = 127; + foo_u32(15); + foo_u32(y); + foo_usize(2394); + foo_usize(15); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/match_loop1.rs b/gcc/testsuite/rust/execute/torture/match_loop1.rs new file mode 100644 index 00000000000..bb6aee946f6 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/match_loop1.rs @@ -0,0 +1,56 @@ +// { dg-output "E::One\nE::Two\nbreak!\n" } + +extern "C" { + fn printf(s: *const i8, ...); +} + +enum E { + One, + Two, + Other, +} + +fn foo() { + let mut x = E::One; + + loop { + match x { + E::One => { + let a = "E::One\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + + x = E::Two; + } + E::Two => { + let a = "E::Two\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + + x = E::Other; + } + _ => { + let a = "break!\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + + break; + } + } + } +} + +fn main() -> i32 { + foo(); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/match_range1.rs b/gcc/testsuite/rust/execute/torture/match_range1.rs new file mode 100644 index 00000000000..82e9e34a989 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/match_range1.rs @@ -0,0 +1,37 @@ +// { dg-output "zero to END_RANGE\nzero to END_RANGE\nelse\n" } + +extern "C" { + fn printf(s: *const i8, ...); +} + +const END_RANGE: i32 = 15; + +fn foo(x: i32) { + match x { + 0..=END_RANGE => { + let a = "zero to END_RANGE\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + } + + _ => { + let a = "else\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + } + } +} + +fn main() -> i32 { + foo(11); + foo(15); + foo(21); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/match_range2.rs b/gcc/testsuite/rust/execute/torture/match_range2.rs new file mode 100644 index 00000000000..8153f9e1c7e --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/match_range2.rs @@ -0,0 +1,45 @@ +// { dg-output "lowercase\nuppercase\nother\n" } + +extern "C" { + fn printf(s: *const i8, ...); +} + +const BIG_A: char = 'A'; +const BIG_Z: char = 'Z'; + +fn bar(x: char) { + match x { + 'a'..='z' => { + let a = "lowercase\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + } + BIG_A..=BIG_Z => { + let a = "uppercase\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + } + _ => { + let a = "other\n\0"; + let b = a as *const str; + let c = b as *const i8; + unsafe { + printf(c); + } + } + } +} + +fn main() -> i32 { + bar('b'); + bar('X'); + bar('!'); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/match_tuple1.rs b/gcc/testsuite/rust/execute/torture/match_tuple1.rs new file mode 100644 index 00000000000..cb61cc0847c --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/match_tuple1.rs @@ -0,0 +1,45 @@ +// { dg-output "x:15\ny:20\n" } + +extern "C" { + fn printf(s: *const i8, ...); +} + +enum Foo { + A, + B, +} + +fn inspect(f: Foo, g: u8) -> i32 { + match (f, g) { + (Foo::A, 1) => { + return 5; + } + + (Foo::A, 2) => { + return 10; + } + + (Foo::B, 2) => { + return 15; + } + + _ => { + return 20; + } + } + return 25; +} + +fn main() -> i32 { + let x = inspect(Foo::B, 2); + let y = inspect(Foo::B, 1); + + unsafe { + printf("x:%d\n" as *const str as *const i8, x); + } + unsafe { + printf("y:%d\n" as *const str as *const i8, y); + } + + y - x - 5 +} diff --git a/gcc/testsuite/rust/execute/torture/method1.rs b/gcc/testsuite/rust/execute/torture/method1.rs new file mode 100644 index 00000000000..6af6133939b --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/method1.rs @@ -0,0 +1,27 @@ +/* { dg-output "124\n458" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +struct Foo(i32); +impl Foo { + fn bar(&self, i: i32) { + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, self.0 + i); + } + } +} + +fn main() -> i32 { + let a = Foo(123); + a.bar(1); + + let b = &Foo(456); + b.bar(2); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/method2.rs b/gcc/testsuite/rust/execute/torture/method2.rs new file mode 100644 index 00000000000..f532b4488c6 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/method2.rs @@ -0,0 +1,76 @@ +// { dg-additional-options "-w" } +// { dg-output "foo_deref\nimm_deref\n" } +extern "C" { + fn printf(s: *const i8, ...); +} + +#[lang = "deref"] +pub trait Deref { + type Target; + + fn deref(&self) -> &Self::Target; +} + +impl Deref for &T { + type Target = T; + + fn deref(&self) -> &T { + unsafe { + let a = "imm_deref\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + *self + } +} + +impl Deref for &mut T { + type Target = T; + + fn deref(&self) -> &T { + unsafe { + let a = "mut_deref\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + *self + } +} + +struct Bar(i32); +impl Bar { + fn foobar(self) -> i32 { + self.0 + } +} + +struct Foo(T); +impl Deref for Foo { + type Target = T; + + fn deref(&self) -> &Self::Target { + unsafe { + let a = "foo_deref\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + &self.0 + } +} + +pub fn main() -> i32 { + let bar = Bar(123); + let foo: Foo<&Bar> = Foo(&bar); + let foobar: i32 = foo.foobar(); + + foobar - 123 +} diff --git a/gcc/testsuite/rust/execute/torture/method3.rs b/gcc/testsuite/rust/execute/torture/method3.rs new file mode 100644 index 00000000000..0e9e8ff42a0 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/method3.rs @@ -0,0 +1,78 @@ +// { dg-additional-options "-w" } +// { dg-output "mut_deref\nfoobar: 123\n" } +extern "C" { + fn printf(s: *const i8, ...); +} + +#[lang = "deref"] +pub trait Deref { + type Target; + + fn deref(&self) -> &Self::Target; +} + +#[lang = "deref_mut"] +pub trait DerefMut: Deref { + fn deref_mut(&mut self) -> &mut Self::Target; +} + +impl Deref for &T { + type Target = T; + + fn deref(&self) -> &T { + *self + } +} + +impl Deref for &mut T { + type Target = T; + fn deref(&self) -> &T { + *self + } +} + +pub struct Bar(i32); +impl Bar { + pub fn foobar(&mut self) -> i32 { + self.0 + } +} + +pub struct Foo(T); +impl Deref for Foo { + type Target = T; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for Foo { + fn deref_mut(&mut self) -> &mut Self::Target { + unsafe { + let a = "mut_deref\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + &mut self.0 + } +} + +pub fn main() -> i32 { + let bar = Bar(123); + let mut foo: Foo = Foo(bar); + let foobar = foo.foobar(); + + unsafe { + let a = "foobar: %i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, foobar); + } + + foobar - 123 +} diff --git a/gcc/testsuite/rust/execute/torture/method4.rs b/gcc/testsuite/rust/execute/torture/method4.rs new file mode 100644 index 00000000000..5c6fdfe02c3 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/method4.rs @@ -0,0 +1,78 @@ +// { dg-additional-options "-w" } +// { dg-output "mut_deref\nfoobar: 123\n" } +extern "C" { + fn printf(s: *const i8, ...); +} + +#[lang = "deref"] +pub trait Deref { + type Target; + + fn deref(&self) -> &Self::Target; +} + +#[lang = "deref_mut"] +pub trait DerefMut: Deref { + fn deref_mut(&mut self) -> &mut Self::Target; +} + +impl Deref for &T { + type Target = T; + + fn deref(&self) -> &T { + *self + } +} + +impl Deref for &mut T { + type Target = T; + fn deref(&self) -> &T { + *self + } +} + +pub struct Bar(i32); +impl Bar { + pub fn foobar(&mut self) -> i32 { + self.0 + } +} + +pub struct Foo(T); +impl Deref for Foo { + type Target = T; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for Foo { + fn deref_mut(&mut self) -> &mut Self::Target { + unsafe { + let a = "mut_deref\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + &mut self.0 + } +} + +pub fn main() -> i32 { + let mut bar = Bar(123); + let mut foo: Foo<&mut Bar> = Foo(&mut bar); + let foobar = foo.foobar(); + + unsafe { + let a = "foobar: %i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, foobar); + } + + foobar - 123 +} diff --git a/gcc/testsuite/rust/execute/torture/mod1.rs b/gcc/testsuite/rust/execute/torture/mod1.rs new file mode 100644 index 00000000000..700393850af --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/mod1.rs @@ -0,0 +1,21 @@ +mod A { + pub mod B { + pub mod C { + pub struct Foo { + pub f: i32, + } + impl Foo { + pub fn new() -> Self { + Foo { f: 23i32 } + } + } + } + } +} + +fn main() -> i32 { + let a = A::B::C::Foo::new(); + let b = A::B::C::Foo { f: -23i32 }; + + a.f + b.f +} diff --git a/gcc/testsuite/rust/execute/torture/modules/mod.rs b/gcc/testsuite/rust/execute/torture/modules/mod.rs new file mode 100644 index 00000000000..9020aaf4bb8 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/modules/mod.rs @@ -0,0 +1,3 @@ +fn return_12() -> i32 { + 12 +} diff --git a/gcc/testsuite/rust/execute/torture/operator_overload_1.rs b/gcc/testsuite/rust/execute/torture/operator_overload_1.rs new file mode 100644 index 00000000000..5a28c5f4e93 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/operator_overload_1.rs @@ -0,0 +1,36 @@ +/* { dg-output "3\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +#[lang = "add"] +pub trait Add { + type Output; + + fn add(self, rhs: Rhs) -> Self::Output; +} + +impl Add for i32 { + type Output = i32; + + fn add(self, other: i32) -> i32 { + let res = self + other; + + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, res); + } + + res + } +} + +fn main() -> i32 { + let a; + a = 1 + 2; + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/operator_overload_10.rs b/gcc/testsuite/rust/execute/torture/operator_overload_10.rs new file mode 100644 index 00000000000..f5d45db5338 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/operator_overload_10.rs @@ -0,0 +1,75 @@ +/* { dg-output "foo_deref\n123\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +#[lang = "deref"] +pub trait Deref { + type Target; + + fn deref(&self) -> &Self::Target; +} + +impl Deref for &T { + type Target = T; + + fn deref(&self) -> &T { + unsafe { + let a = "imm_deref\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + *self + } +} + +impl Deref for &mut T { + type Target = T; + + fn deref(&self) -> &T { + unsafe { + let a = "mut_deref\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + *self + } +} + +struct Foo(T); +impl Deref for Foo { + type Target = T; + + fn deref(&self) -> &Self::Target { + unsafe { + let a = "foo_deref\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + &self.0 + } +} + +fn main() -> i32 { + let foo: Foo = Foo(123); + let bar: i32 = *foo; + + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, bar); + } + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/operator_overload_11.rs b/gcc/testsuite/rust/execute/torture/operator_overload_11.rs new file mode 100644 index 00000000000..1919941c486 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/operator_overload_11.rs @@ -0,0 +1,37 @@ +// { dg-output "1\n" } +// { dg-additional-options "-w" } +extern "C" { + fn printf(s: *const i8, ...); +} + +#[lang = "bitand"] +pub trait BitAnd { + type Output; + + fn bitand(self, rhs: Rhs) -> Self::Output; +} + +impl BitAnd for i32 { + type Output = i32; + + fn bitand(self, other: i32) -> i32 { + let res = self & other; + + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, res); + } + + res + } +} + +fn main() -> i32 { + let a; + a = 1 & 1; + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/operator_overload_12.rs b/gcc/testsuite/rust/execute/torture/operator_overload_12.rs new file mode 100644 index 00000000000..7433330fa31 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/operator_overload_12.rs @@ -0,0 +1,31 @@ +// { dg-output "1\n" } +// { dg-additional-options "-w" } +extern "C" { + fn printf(s: *const i8, ...); +} + +#[lang = "bitand_assign"] +pub trait BitAndAssign { + fn bitand_assign(&mut self, rhs: Rhs); +} + +impl BitAndAssign for i32 { + fn bitand_assign(&mut self, other: i32) { + *self &= other; + + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, *self); + } + } +} + +fn main() -> i32 { + let mut a = 1; + a &= 1; + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/operator_overload_2.rs b/gcc/testsuite/rust/execute/torture/operator_overload_2.rs new file mode 100644 index 00000000000..a577718451d --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/operator_overload_2.rs @@ -0,0 +1,38 @@ +/* { dg-output "3\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +#[lang = "add"] +pub trait Add { + type Output; + + fn add(self, rhs: Rhs) -> Self::Output; +} + +struct Foo(i32); + +impl Add for Foo { + type Output = Foo; + + fn add(self, other: Foo) -> Foo { + let res = Foo(self.0 + other.0); + + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, res.0); + } + + res + } +} + +fn main() -> i32 { + let a; + a = Foo(1) + Foo(2); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/operator_overload_3.rs b/gcc/testsuite/rust/execute/torture/operator_overload_3.rs new file mode 100644 index 00000000000..57f58076c3e --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/operator_overload_3.rs @@ -0,0 +1,55 @@ +/* { dg-output "3\n3\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +#[lang = "add"] +pub trait Add { + type Output; + + fn add(self, rhs: Rhs) -> Self::Output; +} + +impl Add for i32 { + type Output = i32; + + fn add(self, other: i32) -> i32 { + let res = self + other; + + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, res); + } + + res + } +} + +struct Foo(i32); +impl Add for Foo { + type Output = Foo; + + fn add(self, other: Foo) -> Foo { + let res = Foo(self.0 + other.0); + + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, res.0); + } + + res + } +} + +fn main() -> i32 { + let a; + a = Foo(1) + Foo(2); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/operator_overload_4.rs b/gcc/testsuite/rust/execute/torture/operator_overload_4.rs new file mode 100644 index 00000000000..ce9887b2ead --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/operator_overload_4.rs @@ -0,0 +1,33 @@ +/* { dg-output "neg\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +#[lang = "neg"] +pub trait Neg { + type Output; + + fn neg(self) -> Self::Output; +} + +impl Neg for i32 { + type Output = i32; + + fn neg(self) -> i32 { + unsafe { + let a = "neg\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + -self + } +} + +fn main() -> i32 { + let a: i32 = 1; + let _b = -a; + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/operator_overload_5.rs b/gcc/testsuite/rust/execute/torture/operator_overload_5.rs new file mode 100644 index 00000000000..a525f743680 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/operator_overload_5.rs @@ -0,0 +1,33 @@ +/* { dg-output "not\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +#[lang = "not"] +pub trait Not { + type Output; + + fn not(self) -> Self::Output; +} + +impl Not for i32 { + type Output = i32; + + fn not(self) -> i32 { + unsafe { + let a = "not\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + !self + } +} + +fn main() -> i32 { + let a: i32 = 1; + let _b = !a; + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/operator_overload_6.rs b/gcc/testsuite/rust/execute/torture/operator_overload_6.rs new file mode 100644 index 00000000000..fbd2a8fa9d3 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/operator_overload_6.rs @@ -0,0 +1,37 @@ +/* { dg-output "add_assign\n3\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +#[lang = "add_assign"] +pub trait AddAssign { + fn add_assign(&mut self, rhs: Rhs); +} + +impl AddAssign for i32 { + fn add_assign(&mut self, other: i32) { + unsafe { + let a = "add_assign\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + *self += other + } +} + +fn main() -> i32 { + let mut res = 1; + res += 2; + + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, res); + } + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/operator_overload_7.rs b/gcc/testsuite/rust/execute/torture/operator_overload_7.rs new file mode 100644 index 00000000000..886a7010efc --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/operator_overload_7.rs @@ -0,0 +1,42 @@ +/* { dg-output "imm_deref\n123\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +#[lang = "deref"] +pub trait Deref { + type Target; + + fn deref(&self) -> &Self::Target; +} + +impl Deref for &T { + type Target = T; + + fn deref(&self) -> &T { + unsafe { + let a = "imm_deref\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + *self + } +} + +fn main() -> i32 { + let foo: &i32 = &123; + let res: i32 = *foo; + + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, res); + } + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/operator_overload_8.rs b/gcc/testsuite/rust/execute/torture/operator_overload_8.rs new file mode 100644 index 00000000000..862e29a4bc6 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/operator_overload_8.rs @@ -0,0 +1,58 @@ +/* { dg-output "imm_deref\n123\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +#[lang = "deref"] +pub trait Deref { + type Target; + + fn deref(&self) -> &Self::Target; +} + +impl Deref for &T { + type Target = T; + + fn deref(&self) -> &T { + unsafe { + let a = "imm_deref\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + *self + } +} + +impl Deref for &mut T { + type Target = T; + + fn deref(&self) -> &T { + unsafe { + let a = "mut_deref\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + *self + } +} + +fn main() -> i32 { + let foo: &i32 = &123; + let res: i32 = *foo; + + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, res); + } + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/operator_overload_9.rs b/gcc/testsuite/rust/execute/torture/operator_overload_9.rs new file mode 100644 index 00000000000..fd972e28ab3 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/operator_overload_9.rs @@ -0,0 +1,58 @@ +/* { dg-output "mut_deref\n123\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +#[lang = "deref"] +pub trait Deref { + type Target; + + fn deref(&self) -> &Self::Target; +} + +impl Deref for &T { + type Target = T; + + fn deref(&self) -> &T { + unsafe { + let a = "imm_deref\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + *self + } +} + +impl Deref for &mut T { + type Target = T; + + fn deref(&self) -> &T { + unsafe { + let a = "mut_deref\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + + *self + } +} + +fn main() -> i32 { + let foo = &mut 123; + let res: i32 = *foo; + + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, res); + } + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/slice-magic.rs b/gcc/testsuite/rust/execute/torture/slice-magic.rs new file mode 100644 index 00000000000..d1132989ddb --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/slice-magic.rs @@ -0,0 +1,106 @@ +// { dg-additional-options "-w" } +extern "rust-intrinsic" { + #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")] + pub fn offset(dst: *const T, offset: isize) -> *const T; +} + +struct FatPtr { + data: *const T, + len: usize, +} + +union Repr { + rust: *const [T], + rust_mut: *mut [T], + raw: FatPtr, +} + +#[lang = "Range"] +pub struct Range { + pub start: Idx, + pub end: Idx, +} + +#[lang = "const_slice_ptr"] +impl *const [A] { + pub const fn len(self) -> usize { + unsafe { Repr { rust: self }.raw.len } + } + + pub const fn as_ptr(self) -> *const A { + self as *const A + } +} + +#[lang = "const_ptr"] +impl *const B { + pub const unsafe fn offset(self, count: isize) -> *const B { + unsafe { offset(self, count) } + } + + pub const unsafe fn add(self, count: usize) -> Self { + unsafe { self.offset(count as isize) } + } + + pub const fn as_ptr(self) -> *const B { + self as *const B + } +} + +const fn slice_from_raw_parts(data: *const C, len: usize) -> *const [C] { + unsafe { + Repr { + raw: FatPtr { data, len }, + } + .rust + } +} + +#[lang = "index"] +trait Index { + type Output; + + fn index(&self, index: Idx) -> &Self::Output; +} + +pub unsafe trait SliceIndex { + type Output; + + unsafe fn get_unchecked(self, slice: *const X) -> *const Self::Output; + + fn index(self, slice: &X) -> &Self::Output; +} + +unsafe impl SliceIndex<[Y]> for Range { + type Output = [Y]; + + unsafe fn get_unchecked(self, slice: *const [Y]) -> *const [Y] { + unsafe { + let a: *const Y = slice.as_ptr(); + let b: *const Y = a.add(self.start); + slice_from_raw_parts(b, self.end - self.start) + } + } + + fn index(self, slice: &[Y]) -> &[Y] { + unsafe { &*self.get_unchecked(slice) } + } +} + +impl Index for [T] +where + I: SliceIndex<[T]>, +{ + type Output = I::Output; + + fn index(&self, index: I) -> &I::Output { + index.index(self) + } +} + +fn main() -> i32 { + let a = [1, 2, 3, 4, 5]; + let b = &a[1..3]; + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/slice-magic2.rs b/gcc/testsuite/rust/execute/torture/slice-magic2.rs new file mode 100644 index 00000000000..64a566185fa --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/slice-magic2.rs @@ -0,0 +1,106 @@ +// { dg-additional-options "-w" } +extern "rust-intrinsic" { + #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")] + pub fn offset(dst: *const T, offset: isize) -> *const T; +} + +struct FatPtr { + data: *const T, + len: usize, +} + +union Repr { + rust: *const [T], + rust_mut: *mut [T], + raw: FatPtr, +} + +#[lang = "Range"] +pub struct Range { + pub start: Idx, + pub end: Idx, +} + +#[lang = "const_slice_ptr"] +impl *const [T] { + pub const fn len(self) -> usize { + unsafe { Repr { rust: self }.raw.len } + } + + pub const fn as_ptr(self) -> *const T { + self as *const T + } +} + +#[lang = "const_ptr"] +impl *const T { + pub const unsafe fn offset(self, count: isize) -> *const T { + unsafe { offset(self, count) } + } + + pub const unsafe fn add(self, count: usize) -> Self { + unsafe { self.offset(count as isize) } + } + + pub const fn as_ptr(self) -> *const T { + self as *const T + } +} + +const fn slice_from_raw_parts(data: *const T, len: usize) -> *const [T] { + unsafe { + Repr { + raw: FatPtr { data, len }, + } + .rust + } +} + +#[lang = "index"] +trait Index { + type Output; + + fn index(&self, index: Idx) -> &Self::Output; +} + +pub unsafe trait SliceIndex { + type Output; + + unsafe fn get_unchecked(self, slice: *const T) -> *const Self::Output; + + fn index(self, slice: &T) -> &Self::Output; +} + +unsafe impl SliceIndex<[T]> for Range { + 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) } + } +} + +impl Index for [T] +where + I: SliceIndex<[T]>, +{ + type Output = I::Output; + + fn index(&self, index: I) -> &I::Output { + index.index(self) + } +} + +fn main() -> i32 { + let a = [1, 2, 3, 4, 5]; + let b = &a[1..3]; + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/slice1.rs b/gcc/testsuite/rust/execute/torture/slice1.rs new file mode 100644 index 00000000000..a0488b3912c --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/slice1.rs @@ -0,0 +1,27 @@ +// { dg-additional-options "-w" } +struct FatPtr { + data: *const T, + len: usize, +} + +union Repr { + rust: *const [T], + rust_mut: *mut [T], + raw: FatPtr, +} + +const fn slice_from_raw_parts(data: *const T, len: usize) -> *const [T] { + unsafe { + let a = FatPtr { data, len }; + let b = Repr { raw: a }; + b.rust + } +} + +fn main() -> i32 { + let a = 123; + let b: *const i32 = &a; + let c = slice_from_raw_parts(b, 1); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/str-layout1.rs b/gcc/testsuite/rust/execute/torture/str-layout1.rs new file mode 100644 index 00000000000..80bdc2a9c9f --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/str-layout1.rs @@ -0,0 +1,57 @@ +// { dg-additional-options "-w" } +// { dg-output "t1sz=5 t2sz=10" } +mod mem { + extern "rust-intrinsic" { + #[rustc_const_stable(feature = "const_transmute", since = "1.46.0")] + fn transmute(_: T) -> U; + } +} + +extern "C" { + fn printf(s: *const i8, ...); +} + +struct FatPtr { + data: *const T, + len: usize, +} + +pub union Repr { + rust: *const [T], + rust_mut: *mut [T], + raw: FatPtr, +} + +impl [T] { + pub const fn len(&self) -> usize { + unsafe { Repr { rust: self }.raw.len } + } +} + +impl str { + pub const fn len(&self) -> usize { + self.as_bytes().len() + } + + pub const fn as_bytes(&self) -> &[u8] { + unsafe { mem::transmute(self) } + } +} + +fn main() -> i32 { + let t1: &str = "TEST1"; + let t2: &str = &"TEST_12345"; + + let t1sz = t1.len(); + let t2sz = t2.len(); + + unsafe { + let a = "t1sz=%i t2sz=%i\n"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, t1sz as i32, t2sz as i32); + } + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/str-zero.rs b/gcc/testsuite/rust/execute/torture/str-zero.rs new file mode 100644 index 00000000000..e7fba0d1372 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/str-zero.rs @@ -0,0 +1,26 @@ +/* { dg-output "bar foo baz foobar\n" } */ +extern "C" +{ + fn printf(s: *const i8, ...); + fn memchr(s: *const i8, c: u8, n: usize) -> *const i8; +} + +pub fn main () -> i32 +{ + let f = "%s %s %s %s\n\0"; + let s = "bar\0\ + foo\ + \x00\ + baz\u{0000}\ + foobar\0"; + let cf = f as *const str as *const i8; + let cs = s as *const str as *const i8; + unsafe + { + let cs2 = memchr (cs, b'f', 5); + let cs3 = memchr (cs2, b'b', 5); + let cs4 = memchr (cs3, b'f', 5); + printf (cf, cs, cs2, cs3, cs4); + } + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/trait1.rs b/gcc/testsuite/rust/execute/torture/trait1.rs new file mode 100644 index 00000000000..dc3cc471c33 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/trait1.rs @@ -0,0 +1,52 @@ +/* { dg-output "S::f\nT1::f\nT2::f\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +struct S; + +impl S { + fn f() { + unsafe { + let a = "S::f\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + } +} + +trait T1 { + fn f() { + unsafe { + let a = "T1::f\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + } +} +impl T1 for S {} + +trait T2 { + fn f() { + unsafe { + let a = "T2::f\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c); + } + } +} +impl T2 for S {} + +fn main() -> i32 { + S::f(); + ::f(); + ::f(); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/trait10.rs b/gcc/testsuite/rust/execute/torture/trait10.rs new file mode 100644 index 00000000000..e581e324bbf --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/trait10.rs @@ -0,0 +1,41 @@ +/* { dg-output "123\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +struct Foo(i32); +trait Bar { + fn baz(&self); +} + +impl Bar for Foo { + fn baz(&self) { + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, self.0); + } + } +} + +struct S; +impl S { + fn dynamic_dispatch(self, t: &dyn Bar) { + // { dg-warning "unused name" "" { target *-*-* } .-1 } + t.baz(); + } +} + +pub fn main() -> i32 { + let a; + a = &Foo(123); + + let b; + b = S; + + b.dynamic_dispatch(a); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/trait11.rs b/gcc/testsuite/rust/execute/torture/trait11.rs new file mode 100644 index 00000000000..283c9ecd0ed --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/trait11.rs @@ -0,0 +1,38 @@ +/* { dg-output "3\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +trait FnLike { + fn call(&self, arg: A) -> R; +} + +struct S; +impl<'a, T> FnLike<&'a T, &'a T> for S { + fn call(&self, arg: &'a T) -> &'a T { + // { dg-warning "unused name .self." "" { target *-*-* } .-1 } + arg + } +} + +fn indirect(f: F) +where + F: for<'a> FnLike<&'a isize, &'a isize>, +{ + let x = 3; + let y = f.call(&x); + + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, *y); + } +} + +fn main() -> i32 { + indirect(S); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/trait12.rs b/gcc/testsuite/rust/execute/torture/trait12.rs new file mode 100644 index 00000000000..68b0a4014ad --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/trait12.rs @@ -0,0 +1,38 @@ +/* { dg-output "3\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +trait FnLike { + fn call(&self, arg: A) -> R; +} + +type FnObject<'b> = dyn for<'a> FnLike<&'a isize, &'a isize> + 'b; + +struct Identity; + +impl<'a, T> FnLike<&'a T, &'a T> for Identity { + fn call(&self, arg: &'a T) -> &'a T { + // { dg-warning "unused name .self." "" { target *-*-* } .-1 } + arg + } +} + +fn call_repeatedly(f: &FnObject) { + let x = 3; + let y = f.call(&x); + + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, *y); + } +} + +fn main() -> i32 { + call_repeatedly(&Identity); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/trait13.rs b/gcc/testsuite/rust/execute/torture/trait13.rs new file mode 100644 index 00000000000..3071da27a6a --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/trait13.rs @@ -0,0 +1,48 @@ +/* { dg-output "123\n456\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +struct Foo(i32); +trait Bar { + fn baz(&self); + + fn qux(&self) { + // { dg-warning "unused name" "" { target *-*-* } .-1 } + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, 456); + } + } +} + +impl Bar for Foo { + fn baz(&self) { + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, self.0); + } + } +} + +fn dynamic_dispatch(t: &dyn Bar) { + t.baz(); + t.qux(); +} + +fn main() -> i32 { + let a; + a = Foo(123); + + let b: &dyn Bar; + b = &a; + dynamic_dispatch(b); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/trait2.rs b/gcc/testsuite/rust/execute/torture/trait2.rs new file mode 100644 index 00000000000..c96615fa891 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/trait2.rs @@ -0,0 +1,37 @@ +/* { dg-output "Bar::A = 456\n::A = 456\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +trait Foo { + const A: i32 = 123; +} + +struct Bar; +impl Foo for Bar { + const A: i32 = 456; +} + +fn main() -> i32 { + let a; + a = Bar::A; + + unsafe { + let _a = "Bar::A = %i\n\0"; + let _b = _a as *const str; + let _c = _b as *const i8; + printf(_c, a); + } + + let b; + b = ::A; + + unsafe { + let _a = "::A = %i\n\0"; + let _b = _a as *const str; + let _c = _b as *const i8; + printf(_c, b); + } + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/trait3.rs b/gcc/testsuite/rust/execute/torture/trait3.rs new file mode 100644 index 00000000000..accfa9d0a36 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/trait3.rs @@ -0,0 +1,43 @@ +/* { dg-output "123, 777" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +trait A { + fn a() -> i32 { + 123 + } +} + +trait B: A { + fn b() -> i32 { + ::a() + 456 + } +} + +struct T; +// { dg-warning "struct is never constructed" "" { target *-*-* } .-1 } + +impl A for T { + fn a() -> i32 { + 321 + } +} + +struct S; +impl A for S {} +impl B for S {} + +fn main() -> i32 { + let aa = S::a(); + let bb = S::b(); + + unsafe { + let a = "%i, %i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, aa, bb); + } + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/trait4.rs b/gcc/testsuite/rust/execute/torture/trait4.rs new file mode 100644 index 00000000000..8c0d257cd7e --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/trait4.rs @@ -0,0 +1,34 @@ +/* { dg-output "123\n" }*/ +extern "C" { + fn printf(s: *const i8, ...); +} + +struct Foo(i32); +trait Bar { + fn baz(&self); +} + +impl Bar for Foo { + fn baz(&self) { + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, self.0); + } + } +} + +fn type_bound(t: &T) { + t.baz(); +} + +fn main() -> i32 { + let a; + + a = &Foo(123); + type_bound(a); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/trait5.rs b/gcc/testsuite/rust/execute/torture/trait5.rs new file mode 100644 index 00000000000..49f11a6085a --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/trait5.rs @@ -0,0 +1,39 @@ +/* { dg-output "123\n123\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +struct Foo(i32); +trait Bar { + fn baz(&self); +} + +impl Bar for Foo { + fn baz(&self) { + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, self.0); + } + } +} + +fn static_dispatch(t: &T) { + t.baz(); +} + +fn dynamic_dispatch(t: &dyn Bar) { + t.baz(); +} + +fn main() -> i32 { + let a = &Foo(123); + static_dispatch(a); + + let b: &dyn Bar = a; + dynamic_dispatch(b); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/trait6.rs b/gcc/testsuite/rust/execute/torture/trait6.rs new file mode 100644 index 00000000000..c83d6666c87 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/trait6.rs @@ -0,0 +1,39 @@ +/* { dg-output "123\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +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(x: T) -> T::A { + x.bar() +} + +fn main() -> i32 { + let a; + a = S(123); + + let bar: i32 = test_bar::(a); + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, bar); + } + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/trait7.rs b/gcc/testsuite/rust/execute/torture/trait7.rs new file mode 100644 index 00000000000..064f88d5de9 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/trait7.rs @@ -0,0 +1,39 @@ +/* { dg-output "123\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +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(x: T) -> T::A { + x.bar() +} + +fn main() -> i32 { + let a; + a = S(123); + + let bar: i32 = test_bar(a); + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, bar); + } + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/trait8.rs b/gcc/testsuite/rust/execute/torture/trait8.rs new file mode 100644 index 00000000000..14392ff0cca --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/trait8.rs @@ -0,0 +1,39 @@ +/* { dg-output "123\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +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(x: T) -> T::A { + x.bar() +} + +fn main() -> i32 { + let a; + a = S(123); + + let bar: i32 = test_bar(a); + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, bar); + } + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/trait9.rs b/gcc/testsuite/rust/execute/torture/trait9.rs new file mode 100644 index 00000000000..c0e6d36f183 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/trait9.rs @@ -0,0 +1,35 @@ +/* { dg-output "3\n" } */ +extern "C" { + fn printf(s: *const i8, ...); +} + +trait FnLike { + fn call(&self, arg: A) -> R; +} + +struct S; +impl FnLike<&T, &T> for S { + fn call(&self, arg: &T) -> &T { + // { dg-warning "unused name .self." "" { target *-*-* } .-1 } + arg + } +} + +fn indirect>(f: F) { + let x = 3; + let y = f.call(&x); + + unsafe { + let a = "%i\n\0"; + let b = a as *const str; + let c = b as *const i8; + + printf(c, *y); + } +} + +fn main() -> i32 { + indirect(S); + + 0 +} diff --git a/gcc/testsuite/rust/execute/torture/transmute1.rs b/gcc/testsuite/rust/execute/torture/transmute1.rs new file mode 100644 index 00000000000..b9ec38ca618 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/transmute1.rs @@ -0,0 +1,23 @@ +// { dg-additional-options "-w" } + +extern "rust-intrinsic" { + fn transmute(value: T) -> U; +} + +struct WrapI { + inner: i32, +} + +struct WrapF { + inner: f32, +} + +fn main() -> i32 { + let f = 15.4f32; + let f_wrap = WrapF { inner: f }; + + let fst = unsafe { transmute::(f) }; + let snd = unsafe { transmute::(f_wrap) }; + + fst - snd.inner +} diff --git a/gcc/testsuite/rust/execute/torture/wrapping_op1.rs b/gcc/testsuite/rust/execute/torture/wrapping_op1.rs new file mode 100644 index 00000000000..64b37085ab7 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/wrapping_op1.rs @@ -0,0 +1,14 @@ +extern "rust-intrinsic" { + pub fn wrapping_add(l: T, r: T) -> T; +} + +fn five() -> u8 { + 5 +} + +fn main() -> u8 { + let l = 255; + let r = five(); + + unsafe { wrapping_add(l, r) - 4 } +} diff --git a/gcc/testsuite/rust/execute/torture/wrapping_op2.rs b/gcc/testsuite/rust/execute/torture/wrapping_op2.rs new file mode 100644 index 00000000000..f9990157894 --- /dev/null +++ b/gcc/testsuite/rust/execute/torture/wrapping_op2.rs @@ -0,0 +1,20 @@ +extern "rust-intrinsic" { + pub fn wrapping_add(l: T, r: T) -> T; + pub fn wrapping_sub(l: T, r: T) -> T; + pub fn wrapping_mul(l: T, r: T) -> T; +} + +fn five() -> u8 { + 5 +} + +fn main() -> u8 { + let l = 255; + let r = five(); + + let ret0 = unsafe { wrapping_add(l, r) - 4 }; // 4 + let ret1 = unsafe { wrapping_sub(r, l) - 6 }; // 6 + let ret2 = unsafe { wrapping_mul(r, l) - 251 }; // 251 + + ret0 + ret1 + ret2 +} diff --git a/gcc/testsuite/rust/execute/xfail/macro1.rs b/gcc/testsuite/rust/execute/xfail/macro1.rs new file mode 100644 index 00000000000..eab5a0285cf --- /dev/null +++ b/gcc/testsuite/rust/execute/xfail/macro1.rs @@ -0,0 +1,32 @@ +// { dg-output "macro\nmacro\nmacro\nmacro\n" } +extern "C" { + fn printf(s: *const i8, ...); +} + +fn f() { + let r_s = "macro\n\0"; + let s_p = r_s as *const str; + let c_p = s_p as *const i8; + + printf(c_p); +} + +macro_rules! empty0 { + () => ( f() ); +} + +macro_rules! empty1 { + {} => { f() }; +} + +macro_rules! empty2 { + [] => [ f() ]; +} + +// using multiple parens/brackets/curlies variants allows us to make sure we +// parse everything properly +fn main() { + empty0!(); + empty1!{}; + empty2![]; +} From patchwork Wed Aug 24 11:59:26 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: herron.philip@googlemail.com X-Patchwork-Id: 56985 Return-Path: X-Original-To: patchwork@sourceware.org Delivered-To: patchwork@sourceware.org Received: from server2.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id A3583395380B for ; Wed, 24 Aug 2022 12:02:56 +0000 (GMT) X-Original-To: gcc-patches@gcc.gnu.org Delivered-To: gcc-patches@gcc.gnu.org Received: from mail-wm1-x332.google.com (mail-wm1-x332.google.com [IPv6:2a00:1450:4864:20::332]) by sourceware.org (Postfix) with ESMTPS id 4552E384D15A; Wed, 24 Aug 2022 12:00:36 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.1 sourceware.org 4552E384D15A Authentication-Results: sourceware.org; dmarc=pass (p=quarantine dis=none) header.from=googlemail.com Authentication-Results: sourceware.org; spf=pass smtp.mailfrom=googlemail.com Received: by mail-wm1-x332.google.com with SMTP id m17-20020a7bce11000000b003a5bedec07bso801497wmc.0; Wed, 24 Aug 2022 05:00:36 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=googlemail.com; s=20210112; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc; bh=8T8GbiKhgPYZRZV5H23CKHO8b5/0wiJQ2GCgfG67Ky8=; b=QLC2UNlzph6Km+OgDBuwIq2ecgQeX8Ybc7pPwDUorIkhTMSKqH7g2mnZXpKPoxlIYb XmLObD0984ywRfRUqN2CrJYzdP4r0datzSejob+m+/gOgqecdTRtZaMfsZ4Xde26VKX6 6MY3Qe1zHyBBX53CCrmthv9AU9LxD21ctpgVOb3X5muH08SkLbZcY4d1MQKjjk77CaaV 4RZb7Wp8u9nmdvZkRMR287Ms4jZTI5eJ6NCNNEbKG9/4/L1DrjXn9QwZd7wonnFUCtGa DfQVLmI1aI2IGV8fCH3X6Q5nbqdS4JVItQXaajrFMva8vwvfGGzRAaEWs55xmaMy+9cg M8ig== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc; bh=8T8GbiKhgPYZRZV5H23CKHO8b5/0wiJQ2GCgfG67Ky8=; b=kLK6wgs+V/U2NE8E/955sKxnUaiDYf+C2rV7zmmw9KNuGB9eEfNO4vCtsFqlN1pwY+ S6yZa+mjT/4QnXENnL233ajGPWxvl652YAMPt7GW8RhQGzMVeSHbYoIrjAi8Fs1Myb8h HpvxomCFXw6FaRKkrAhmh1NjG5iZjK26mbwiyVuhxu49DP8xnAkFLoNl2W5coZ2rSxg3 Lx0e0hAwIPcbBj3A/9uTSZY7Rle6Bxkj7N0TEWmpxDVeZFTyESe95si9uxVeZPdsx8pu X2VOvw7FdZ0LnoGavT5ptugqjwFdFJazkswxQDKZY72WZUHp5GPnk5Abka23rN7MjwDd ZEqA== X-Gm-Message-State: ACgBeo1X8aY9ykKMLoCUAcBoy+f7oVTU31Dhd14zol9DKhtG8rm+c+PT a6jL919TvM5L3LTNljjXfWSVGrp0toY= X-Google-Smtp-Source: AA6agR7sawz94aKbN/dUjgWQC2ZLUqmZfnE4bxcmdrboUygSRejCEUojIP/q1m9InpfV1uldeM0Jig== X-Received: by 2002:a05:600c:501f:b0:3a5:54ff:625f with SMTP id n31-20020a05600c501f00b003a554ff625fmr5191967wmr.5.1661342434830; Wed, 24 Aug 2022 05:00:34 -0700 (PDT) Received: from localhost.localdomain ([86.14.124.218]) by smtp.gmail.com with ESMTPSA id cc19-20020a5d5c13000000b0022571d43d32sm1697676wrb.21.2022.08.24.05.00.33 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 24 Aug 2022 05:00:34 -0700 (PDT) From: herron.philip@googlemail.com X-Google-Original-From: philip.herron@embecosm.com To: gcc-patches@gcc.gnu.org Subject: [PATCH Rust front-end v2 07/37] gccrs: Add gcc-check-target check-rust Date: Wed, 24 Aug 2022 12:59:26 +0100 Message-Id: <20220824115956.737931-8-philip.herron@embecosm.com> X-Mailer: git-send-email 2.25.1 In-Reply-To: <20220824115956.737931-1-philip.herron@embecosm.com> References: <20220824115956.737931-1-philip.herron@embecosm.com> MIME-Version: 1.0 X-Spam-Status: No, score=-11.3 required=5.0 tests=BAYES_00, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, DKIM_VALID_EF, FREEMAIL_FROM, GIT_PATCH_0, RCVD_IN_DNSWL_NONE, SPF_HELO_NONE, SPF_PASS, TXREP, T_SCC_BODY_TEXT_LINE autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on server2.sourceware.org X-BeenThere: gcc-patches@gcc.gnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: Gcc-patches mailing list List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Reply-To: philip.herron@embecosm.com Cc: gcc-rust@gcc.gnu.org, Philip Herron Errors-To: gcc-patches-bounces+patchwork=sourceware.org@gcc.gnu.org Sender: "Gcc-patches" From: Philip Herron This allows us to invoke the rust testsuite. ChangeLog: * Makefile.def: Add autogen target * Makefile.in: regenerate via autogen --- Makefile.def | 1 + Makefile.in | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/Makefile.def b/Makefile.def index 3291b126b26..821016af3a2 100644 --- a/Makefile.def +++ b/Makefile.def @@ -681,6 +681,7 @@ languages = { language=go; gcc-check-target=check-go; languages = { language=d; gcc-check-target=check-d; lib-check-target=check-target-libphobos; }; languages = { language=jit; gcc-check-target=check-jit; }; +languages = { language=rust; gcc-check-target=check-rust; }; // Toplevel bootstrap bootstrap_stage = { id=1 ; }; diff --git a/Makefile.in b/Makefile.in index 1919dfee829..9ed2c0dec52 100644 --- a/Makefile.in +++ b/Makefile.in @@ -60583,6 +60583,14 @@ check-gcc-jit: (cd gcc && $(MAKE) $(GCC_FLAGS_TO_PASS) check-jit); check-jit: check-gcc-jit +.PHONY: check-gcc-rust check-rust +check-gcc-rust: + r=`${PWD_COMMAND}`; export r; \ + s=`cd $(srcdir); ${PWD_COMMAND}`; export s; \ + $(HOST_EXPORTS) \ + (cd gcc && $(MAKE) $(GCC_FLAGS_TO_PASS) check-rust); +check-rust: check-gcc-rust + # The gcc part of install-no-fixedincludes, which relies on an intimate # knowledge of how a number of gcc internal targets (inter)operate. Delegate. From patchwork Wed Aug 24 11:59:28 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: herron.philip@googlemail.com X-Patchwork-Id: 56979 Return-Path: X-Original-To: patchwork@sourceware.org Delivered-To: patchwork@sourceware.org Received: from server2.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id 6CC2C384C001 for ; Wed, 24 Aug 2022 12:01:27 +0000 (GMT) X-Original-To: gcc-patches@gcc.gnu.org Delivered-To: gcc-patches@gcc.gnu.org Received: from mail-wr1-x434.google.com (mail-wr1-x434.google.com [IPv6:2a00:1450:4864:20::434]) by sourceware.org (Postfix) with ESMTPS id 69C6F3851160; Wed, 24 Aug 2022 12:00:42 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.1 sourceware.org 69C6F3851160 Authentication-Results: sourceware.org; dmarc=pass (p=quarantine dis=none) header.from=googlemail.com Authentication-Results: sourceware.org; spf=pass smtp.mailfrom=googlemail.com Received: by mail-wr1-x434.google.com with SMTP id k9so20508511wri.0; Wed, 24 Aug 2022 05:00:42 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=googlemail.com; s=20210112; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc; bh=45iNqmyUxhCeI7HmM8WLC1wQEUfiNNjC7AKM0nRHaTY=; b=YxU1J2OtU6M94thhg9Bye/iTIfVFjAeXmt08fAtSx3P0de3VanHDBT3s4F2aC1U1j6 6CNxllXgsQWpJ66HpKqXKBROAkPjTDoUe5G09q1/OzrQ5iXZigQEz31IMLUIWwqRzeO/ CjwBGQCmTNuQ39ekchhhxjqmdGODqRgXWEF2E+2PdrI1aOoUx30HMD5h32X9dB0muQM4 7BS2OItKRZsbFq3YxWZqNlM86bhxos/K8j+64oN768vFblAduKDJvzAYrVcDNggtjR1G 06btLWbBjKhA6GfTFvBhjaBG9F6afJqyHyKSwcICwxo2/5T+8FZjFkFAYKGe2pa2My8p xYng== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc; bh=45iNqmyUxhCeI7HmM8WLC1wQEUfiNNjC7AKM0nRHaTY=; b=eGqFeQQE0HBfAfjFWOIsg+7gT6Gp9NYlECms8oW75yZYiip8dp1TMmHHhLYnl1yXkw HxBqOFfZcz0b9AP9QO5xv4zGe/7c2vdR8RoKepSZmA1ZYV1qqTk0Ygk9d2eKHKS82ZLN MZHlHA6NW0pljONQrZDl8LcyZ/TAIb/QL9AyR6oiV0WFAXWZfdtzlibUUvBNMu+sdHzn e4tbErPo+ASa2Ercu2LYB5bFTLJIzUgvS2pXM9TgBWVksc3bixESo9JZXBK4xpxCBkbT Pw8VAxT3VE4emFc6wrbLyGo3eiohbI6rOxWlHBzIw9ua1nKoknzjjsrTvo/tpx13sKVD yZ0g== X-Gm-Message-State: ACgBeo2PqZul4br6WKAy70eIICyoERMGVtZf8NsF5XXcvH8RY7gNyRRq T4T/5ihnzyKOCUVr03Qs48d/4tNN7/8= X-Google-Smtp-Source: AA6agR7Uh6G+ughX0ukPHIWANqDYyQ9sYwxO3rD4tSiOy8kuBBGwDsTCidJy8bXo/5g9oeFDAkjm2Q== X-Received: by 2002:a05:6000:12c3:b0:225:3063:82a6 with SMTP id l3-20020a05600012c300b00225306382a6mr14813095wrx.541.1661342438967; Wed, 24 Aug 2022 05:00:38 -0700 (PDT) Received: from localhost.localdomain ([86.14.124.218]) by smtp.gmail.com with ESMTPSA id cc19-20020a5d5c13000000b0022571d43d32sm1697676wrb.21.2022.08.24.05.00.38 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 24 Aug 2022 05:00:38 -0700 (PDT) From: herron.philip@googlemail.com X-Google-Original-From: philip.herron@embecosm.com To: gcc-patches@gcc.gnu.org Subject: [PATCH Rust front-end v2 09/37] gccrs: Add Lexer for Rust front-end Date: Wed, 24 Aug 2022 12:59:28 +0100 Message-Id: <20220824115956.737931-10-philip.herron@embecosm.com> X-Mailer: git-send-email 2.25.1 In-Reply-To: <20220824115956.737931-1-philip.herron@embecosm.com> References: <20220824115956.737931-1-philip.herron@embecosm.com> MIME-Version: 1.0 X-Spam-Status: No, score=-11.2 required=5.0 tests=BAYES_00, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, DKIM_VALID_EF, FREEMAIL_FROM, GIT_PATCH_0, KAM_SHORT, RCVD_IN_DNSWL_NONE, SPF_HELO_NONE, SPF_PASS, TXREP, T_SCC_BODY_TEXT_LINE autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on server2.sourceware.org X-BeenThere: gcc-patches@gcc.gnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: Gcc-patches mailing list List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Reply-To: philip.herron@embecosm.com Cc: The Other , Arthur Cohen , Mark Wielaard , gcc-rust@gcc.gnu.org, Philip Herron Errors-To: gcc-patches-bounces+patchwork=sourceware.org@gcc.gnu.org Sender: "Gcc-patches" From: The Other The lexer is refered to as a ManagedTokenSource within the parser, this lexer does not currently support unicode but serves as a starting point to do so. Co-authored-by: Philip Herron Co-authored-by: Arthur Cohen Co-authored-by: Mark Wielaard --- gcc/rust/lex/rust-codepoint.h | 46 + gcc/rust/lex/rust-lex.cc | 2729 ++++++++++++++++++++++++++++++++ gcc/rust/lex/rust-lex.h | 271 ++++ gcc/rust/lex/rust-token.cc | 135 ++ gcc/rust/lex/rust-token.h | 455 ++++++ gcc/rust/rust-buffered-queue.h | 204 +++ 6 files changed, 3840 insertions(+) create mode 100644 gcc/rust/lex/rust-codepoint.h create mode 100644 gcc/rust/lex/rust-lex.cc create mode 100644 gcc/rust/lex/rust-lex.h create mode 100644 gcc/rust/lex/rust-token.cc create mode 100644 gcc/rust/lex/rust-token.h create mode 100644 gcc/rust/rust-buffered-queue.h diff --git a/gcc/rust/lex/rust-codepoint.h b/gcc/rust/lex/rust-codepoint.h new file mode 100644 index 00000000000..22da080bbb2 --- /dev/null +++ b/gcc/rust/lex/rust-codepoint.h @@ -0,0 +1,46 @@ +// Copyright (C) 2020-2022 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 +// . + +#ifndef RUST_CODEPOINT_H +#define RUST_CODEPOINT_H + +#include + +namespace Rust { +struct Codepoint +{ + uint32_t value; + + // Creates a zero codepoint. + Codepoint () : value (0) {} + + // Creates a codepoint from an encoded UTF-8 value. + Codepoint (uint32_t value) : value (value) {} + + static Codepoint eof () { return Codepoint (UINT32_MAX); } + bool is_eof () const { return value == UINT32_MAX; } + + // Returns a C++ string containing string value of codepoint. + std::string as_string (); + + bool operator== (Codepoint other) const { return value == other.value; } + bool operator!= (Codepoint other) const { return !operator== (other); } +}; +} // namespace Rust + +#endif diff --git a/gcc/rust/lex/rust-lex.cc b/gcc/rust/lex/rust-lex.cc new file mode 100644 index 00000000000..70e6b50209f --- /dev/null +++ b/gcc/rust/lex/rust-lex.cc @@ -0,0 +1,2729 @@ +// Copyright (C) 2020-2022 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 +// . + +#include "rust-lex.h" + +#include "rust-system.h" // for rust_assert and rust_unreachable +#include "rust-diagnostics.h" // for rust_error_at +#include "rust-linemap.h" +#include "rust-session-manager.h" +#include "safe-ctype.h" + +namespace Rust { +// TODO: move to separate compilation unit? +// overload += for uint32_t to allow 32-bit encoded utf-8 to be added +std::string & +operator+= (std::string &str, Codepoint char32) +{ + if (char32.value < 0x80) + { + str += static_cast (char32.value); + } + else if (char32.value < (0x1F + 1) << (1 * 6)) + { + str += static_cast (0xC0 | ((char32.value >> 6) & 0x1F)); + str += static_cast (0x80 | ((char32.value >> 0) & 0x3F)); + } + else if (char32.value < (0x0F + 1) << (2 * 6)) + { + str += static_cast (0xE0 | ((char32.value >> 12) & 0x0F)); + str += static_cast (0x80 | ((char32.value >> 6) & 0x3F)); + str += static_cast (0x80 | ((char32.value >> 0) & 0x3F)); + } + else if (char32.value < (0x07 + 1) << (3 * 6)) + { + str += static_cast (0xF0 | ((char32.value >> 18) & 0x07)); + str += static_cast (0x80 | ((char32.value >> 12) & 0x3F)); + str += static_cast (0x80 | ((char32.value >> 6) & 0x3F)); + str += static_cast (0x80 | ((char32.value >> 0) & 0x3F)); + } + else + { + rust_debug ("Invalid unicode codepoint found: '%u' ", char32.value); + } + return str; +} + +std::string +Codepoint::as_string () +{ + std::string str; + + // str += Codepoint (value); + str += *this; + + return str; +} + +/* Includes all allowable float digits EXCEPT _ and . as that needs lookahead + * for handling. */ +bool +is_float_digit (char number) +{ + return ISDIGIT (number) || number == 'E' || number == 'e'; +} + +/* Basically ISXDIGIT from safe-ctype but may change if Rust's encoding or + * whatever is different */ +bool +is_x_digit (char number) +{ + return ISXDIGIT (number); +} + +bool +is_octal_digit (char number) +{ + return number >= '0' && number <= '7'; +} + +bool +is_bin_digit (char number) +{ + return number == '0' || number == '1'; +} + +bool +check_valid_float_dot_end (char character) +{ + return character != '.' && character != '_' && !ISALPHA (character); +} + +// ISSPACE from safe-ctype but may change in future +bool +is_whitespace (char character) +{ + return ISSPACE (character); +} + +bool +is_non_decimal_int_literal_separator (char character) +{ + return character == 'x' || character == 'o' || character == 'b'; +} + +Lexer::Lexer (const std::string &input) + : input (RAIIFile::create_error ()), current_line (1), current_column (1), + line_map (nullptr), raw_input_source (new BufferInputSource (input, 0)), + input_queue{*raw_input_source}, token_queue (TokenSource (this)) +{} + +Lexer::Lexer (const char *filename, RAIIFile file_input, Linemap *linemap) + : input (std::move (file_input)), current_line (1), current_column (1), + line_map (linemap), + raw_input_source (new FileInputSource (input.get_raw ())), + input_queue{*raw_input_source}, token_queue (TokenSource (this)) +{ + // inform line_table that file is being entered and is in line 1 + if (linemap) + line_map->start_file (filename, current_line); +} + +Lexer::~Lexer () +{ + /* ok apparently stop (which is equivalent of original code in destructor) is + * meant to be called after all files have finished parsing, for cleanup. On + * the other hand, actual code that it calls to leave a certain line map is + * mentioned in GCC docs as being useful for "just leaving an included header" + * and stuff like that, so this line mapping functionality may need fixing. + * FIXME: find out whether this occurs. */ + + // line_map->stop(); +} + +/* TODO: need to optimise somehow to avoid the virtual function call in the + * tight loop. Best idea at the moment is CRTP, but that might make lexer + * implementation annoying when storing the "base class" (i.e. would need + * template parameter everywhere), although in practice it would mostly just + * look ugly and make enclosing classes like Parser also require a type + * parameter. At this point a macro might be better. OK I guess macros can be + * replaced by constexpr if or something if possible. */ +Location +Lexer::get_current_location () +{ + if (line_map) + return line_map->get_location (current_column); + else + // If we have no linemap, we're lexing something without proper locations + return Location (); +} + +int +Lexer::peek_input (int n) +{ + return input_queue.peek (n); +} + +int +Lexer::peek_input () +{ + return peek_input (0); +} + +void +Lexer::skip_input (int n) +{ + input_queue.skip (n); +} + +void +Lexer::skip_input () +{ + skip_input (0); +} + +void +Lexer::replace_current_token (TokenPtr replacement) +{ + token_queue.replace_current_value (replacement); + + rust_debug ("called 'replace_current_token' - this is deprecated"); +} + +/* shitty anonymous namespace that can only be accessed inside the compilation + * unit - used for classify_keyword binary search in sorted array of keywords + * created with x-macros. */ +namespace { +// TODO: make constexpr when update to c++20 +const std::string keyword_index[] = { +#define RS_TOKEN(x, y) +#define RS_TOKEN_KEYWORD(name, keyword) keyword, + RS_TOKEN_LIST +#undef RS_TOKEN_KEYWORD +#undef RS_TOKEN +}; + +constexpr TokenId keyword_keys[] = { +#define RS_TOKEN(x, y) +#define RS_TOKEN_KEYWORD(name, keyword) name, + RS_TOKEN_LIST +#undef RS_TOKEN_KEYWORD +#undef RS_TOKEN +}; + +constexpr int num_keywords = sizeof (keyword_index) / sizeof (*keyword_index); +} // namespace + +/* Determines whether the string passed in is a keyword or not. If it is, it + * returns the keyword name. */ +TokenId +Lexer::classify_keyword (const std::string &str) +{ + const std::string *last = keyword_index + num_keywords; + const std::string *idx = std::lower_bound (keyword_index, last, str); + + if (idx == last || str != *idx) + return IDENTIFIER; + + // TODO: possibly replace this x-macro system with something like hash map? + + // We now have the expected token ID of the reserved keyword. However, some + // keywords are reserved starting in certain editions. For example, `try` is + // only a reserved keyword in editions >=2018. The language might gain new + // reserved keywords in the future. + // + // https://doc.rust-lang.org/reference/keywords.html#reserved-keywords + auto id = keyword_keys[idx - keyword_index]; + + // `try` is not a reserved keyword before 2018 + if (Session::get_instance ().options.get_edition () + == CompileOptions::Edition::E2015 + && id == TRY) + return IDENTIFIER; + + return id; +} + +TokenPtr +Lexer::build_token () +{ + // loop to go through multiple characters to build a single token + while (true) + { + Location loc = get_current_location (); + current_char = peek_input (); + skip_input (); + + // detect UTF8 bom + // + // Must be the first thing on the first line. + // There might be an optional BOM (Byte Order Mark), which for UTF-8 is + // the three bytes 0xEF, 0xBB and 0xBF. These can simply be skipped. + if (current_line == 1 && current_column == 1 && current_char == 0xef + && peek_input () == 0xbb && peek_input (1) == 0xbf) + { + skip_input (1); + current_char = peek_input (); + skip_input (); + } + + // detect shebang + // Must be the first thing on the first line, starting with #! + // But since an attribute can also start with an #! we don't count it as a + // shebang line when after any whitespace or comments there is a [. If it + // is a shebang line we simple drop the line. Otherwise we don't consume + // any characters and fall through to the real tokenizer. + if (current_line == 1 && current_column == 1 && current_char == '#' + && peek_input () == '!') + { + int n = 1; + while (true) + { + int next_char = peek_input (n); + if (is_whitespace (next_char)) + n++; + else if ((next_char == '/' && peek_input (n + 1) == '/' + && peek_input (n + 2) != '!' + && peek_input (n + 2) != '/') + || (next_char == '/' && peek_input (n + 1) == '/' + && peek_input (n + 2) == '/' + && peek_input (n + 3) == '/')) + { + // two // or four //// + // A single line comment + // (but not an inner or outer doc comment) + n += 2; + next_char = peek_input (n); + while (next_char != '\n' && next_char != EOF) + { + n++; + next_char = peek_input (n); + } + if (next_char == '\n') + n++; + } + else if (next_char == '/' && peek_input (n + 1) == '*' + && peek_input (n + 2) == '*' + && peek_input (n + 3) == '/') + { + /**/ + n += 4; + } + else if (next_char == '/' && peek_input (n + 1) == '*' + && peek_input (n + 2) == '*' && peek_input (n + 3) == '*' + && peek_input (n + 4) == '/') + { + /***/ + n += 5; + } + else if ((next_char == '/' && peek_input (n + 1) == '*' + && peek_input (n + 2) != '*' + && peek_input (n + 2) != '!') + || (next_char == '/' && peek_input (n + 1) == '*' + && peek_input (n + 2) == '*' + && peek_input (n + 3) == '*')) + { + // one /* or three /*** + // Start of a block comment + // (but not an inner or outer doc comment) + n += 2; + int level = 1; + while (level > 0) + { + if (peek_input (n) == EOF) + break; + else if (peek_input (n) == '/' + && peek_input (n + 1) == '*') + { + n += 2; + level += 1; + } + else if (peek_input (n) == '*' + && peek_input (n + 1) == '/') + { + n += 2; + level -= 1; + } + else + n++; + } + } + else if (next_char != '[') + { + // definitely shebang, ignore the first line + while (current_char != '\n' && current_char != EOF) + { + current_char = peek_input (); + skip_input (); + } + + // newline + current_line++; + current_column = 1; + // tell line_table that new line starts + start_line (current_line, max_column_hint); + break; + } + else + break; /* Definitely not a shebang line. */ + } + } + + // return end of file token if end of file + if (current_char == EOF) + return Token::make (END_OF_FILE, loc); + + // if not end of file, start tokenising + switch (current_char) + { + /* ignore whitespace characters for tokens but continue updating + * location */ + case '\n': // newline + current_line++; + current_column = 1; + // tell line_table that new line starts + start_line (current_line, max_column_hint); + continue; + case '\r': // cr + // Ignore, we expect a newline (lf) soon. + continue; + case ' ': // space + current_column++; + continue; + case '\t': // tab + // width of a tab is not well-defined, assume 8 spaces + current_column += 8; + continue; + + // punctuation - actual tokens + case '=': + if (peek_input () == '>') + { + // match arm arrow + skip_input (); + current_column += 2; + + return Token::make (MATCH_ARROW, loc); + } + else if (peek_input () == '=') + { + // equality operator + skip_input (); + current_column += 2; + + return Token::make (EQUAL_EQUAL, loc); + } + else + { + // assignment operator + current_column++; + return Token::make (EQUAL, loc); + } + case '(': + current_column++; + return Token::make (LEFT_PAREN, loc); + case '-': + if (peek_input () == '>') + { + // return type specifier + skip_input (); + current_column += 2; + + return Token::make (RETURN_TYPE, loc); + } + else if (peek_input () == '=') + { + // minus-assign + skip_input (); + current_column += 2; + + return Token::make (MINUS_EQ, loc); + } + else + { + // minus + current_column++; + return Token::make (MINUS, loc); + } + case '+': + if (peek_input () == '=') + { + // add-assign + skip_input (); + current_column += 2; + + return Token::make (PLUS_EQ, loc); + } + else + { + // add + current_column++; + return Token::make (PLUS, loc); + } + case ')': + current_column++; + return Token::make (RIGHT_PAREN, loc); + case ';': + current_column++; + return Token::make (SEMICOLON, loc); + case '*': + if (peek_input () == '=') + { + // multiplication-assign + skip_input (); + current_column += 2; + + return Token::make (ASTERISK_EQ, loc); + } + else + { + // multiplication + current_column++; + return Token::make (ASTERISK, loc); + } + case ',': + current_column++; + return Token::make (COMMA, loc); + case '/': + if (peek_input () == '=') + { + // division-assign + skip_input (); + current_column += 2; + + return Token::make (DIV_EQ, loc); + } + else if ((peek_input () == '/' && peek_input (1) != '!' + && peek_input (1) != '/') + || (peek_input () == '/' && peek_input (1) == '/' + && peek_input (2) == '/')) + { + // two // or four //// + // single line comment + // (but not an inner or outer doc comment) + skip_input (); + current_column += 2; + current_char = peek_input (); + + // basically ignore until line finishes + while (current_char != '\n' && current_char != EOF) + { + skip_input (); + current_column++; // not used + current_char = peek_input (); + } + continue; + } + else if (peek_input () == '/' + && (peek_input (1) == '!' || peek_input (1) == '/')) + { + /* single line doc comment, inner or outer. */ + bool is_inner = peek_input (1) == '!'; + skip_input (1); + current_column += 3; + + std::string str; + str.reserve (32); + current_char = peek_input (); + while (current_char != '\n') + { + skip_input (); + if (current_char == '\r') + { + char next_char = peek_input (); + if (next_char == '\n') + { + current_char = '\n'; + break; + } + rust_error_at ( + loc, "Isolated CR %<\\r%> not allowed in doc comment"); + current_char = next_char; + continue; + } + if (current_char == EOF) + { + rust_error_at ( + loc, "unexpected EOF while looking for end of comment"); + break; + } + str += current_char; + current_char = peek_input (); + } + skip_input (); + current_line++; + current_column = 1; + // tell line_table that new line starts + start_line (current_line, max_column_hint); + + str.shrink_to_fit (); + if (is_inner) + return Token::make_inner_doc_comment (loc, std::move (str)); + else + return Token::make_outer_doc_comment (loc, std::move (str)); + } + else if (peek_input () == '*' && peek_input (1) == '*' + && peek_input (2) == '/') + { + /**/ + skip_input (2); + current_column += 4; + continue; + } + else if (peek_input () == '*' && peek_input (1) == '*' + && peek_input (2) == '*' && peek_input (3) == '/') + { + /***/ + skip_input (3); + current_column += 5; + continue; + } + else if ((peek_input () == '*' && peek_input (1) != '!' + && peek_input (1) != '*') + || (peek_input () == '*' && peek_input (1) == '*' + && peek_input (2) == '*')) + { + // one /* or three /*** + // block comment + // (but not an inner or outer doc comment) + skip_input (); + current_column += 2; + + int level = 1; + while (level > 0) + { + current_char = peek_input (); + + if (current_char == EOF) + { + rust_error_at ( + loc, "unexpected EOF while looking for end of comment"); + break; + } + + // if /* found + if (current_char == '/' && peek_input (1) == '*') + { + // skip /* characters + skip_input (1); + + current_column += 2; + + level += 1; + continue; + } + + // ignore until */ is found + if (current_char == '*' && peek_input (1) == '/') + { + // skip */ characters + skip_input (1); + + current_column += 2; + + level -= 1; + continue; + } + + if (current_char == '\n') + { + skip_input (); + current_line++; + current_column = 1; + // tell line_table that new line starts + start_line (current_line, max_column_hint); + continue; + } + + skip_input (); + current_column++; + } + + // refresh new token + continue; + } + else if (peek_input () == '*' + && (peek_input (1) == '!' || peek_input (1) == '*')) + { + // block doc comment, inner /*! or outer /** + bool is_inner = peek_input (1) == '!'; + skip_input (1); + current_column += 3; + + std::string str; + str.reserve (96); + + int level = 1; + while (level > 0) + { + current_char = peek_input (); + + if (current_char == EOF) + { + rust_error_at ( + loc, "unexpected EOF while looking for end of comment"); + break; + } + + // if /* found + if (current_char == '/' && peek_input (1) == '*') + { + // skip /* characters + skip_input (1); + current_column += 2; + + level += 1; + str += "/*"; + continue; + } + + // ignore until */ is found + if (current_char == '*' && peek_input (1) == '/') + { + // skip */ characters + skip_input (1); + current_column += 2; + + level -= 1; + if (level > 0) + str += "*/"; + continue; + } + + if (current_char == '\r' && peek_input (1) != '\n') + rust_error_at ( + loc, "Isolated CR %<\\r%> not allowed in doc comment"); + + if (current_char == '\n') + { + skip_input (); + current_line++; + current_column = 1; + // tell line_table that new line starts + start_line (current_line, max_column_hint); + str += '\n'; + continue; + } + + str += current_char; + skip_input (); + current_column++; + } + + str.shrink_to_fit (); + if (is_inner) + return Token::make_inner_doc_comment (loc, std::move (str)); + else + return Token::make_outer_doc_comment (loc, std::move (str)); + } + else + { + // division + current_column++; + return Token::make (DIV, loc); + } + case '%': + if (peek_input () == '=') + { + // modulo-assign + skip_input (); + current_column += 2; + + return Token::make (PERCENT_EQ, loc); + } + else + { + // modulo + current_column++; + return Token::make (PERCENT, loc); + } + case '^': + if (peek_input () == '=') + { + // xor-assign? + skip_input (); + current_column += 2; + + return Token::make (CARET_EQ, loc); + } + else + { + // xor? + current_column++; + return Token::make (CARET, loc); + } + case '<': + if (peek_input () == '<') + { + if (peek_input (1) == '=') + { + // left-shift assign + skip_input (1); + current_column += 3; + + return Token::make (LEFT_SHIFT_EQ, loc); + } + else + { + // left-shift + skip_input (); + current_column += 2; + + return Token::make (LEFT_SHIFT, loc); + } + } + else if (peek_input () == '=') + { + // smaller than or equal to + skip_input (); + current_column += 2; + + return Token::make (LESS_OR_EQUAL, loc); + } + else + { + // smaller than + current_column++; + return Token::make (LEFT_ANGLE, loc); + } + break; + case '>': + if (peek_input () == '>') + { + if (peek_input (1) == '=') + { + // right-shift-assign + skip_input (1); + current_column += 3; + + return Token::make (RIGHT_SHIFT_EQ, loc); + } + else + { + // right-shift + skip_input (); + current_column += 2; + + return Token::make (RIGHT_SHIFT, loc); + } + } + else if (peek_input () == '=') + { + // larger than or equal to + skip_input (); + current_column += 2; + + return Token::make (GREATER_OR_EQUAL, loc); + } + else + { + // larger than + current_column++; + return Token::make (RIGHT_ANGLE, loc); + } + case ':': + if (peek_input () == ':') + { + // scope resolution :: + skip_input (); + current_column += 2; + + return Token::make (SCOPE_RESOLUTION, loc); + } + else + { + // single colon : + current_column++; + return Token::make (COLON, loc); + } + case '!': + // no special handling for macros in lexer? + if (peek_input () == '=') + { + // not equal boolean operator + skip_input (); + current_column += 2; + + return Token::make (NOT_EQUAL, loc); + } + else + { + // not equal unary operator + current_column++; + + return Token::make (EXCLAM, loc); + } + case '?': + current_column++; + return Token::make (QUESTION_MARK, loc); + case '#': + current_column++; + return Token::make (HASH, loc); + case '[': + current_column++; + return Token::make (LEFT_SQUARE, loc); + case ']': + current_column++; + return Token::make (RIGHT_SQUARE, loc); + case '{': + current_column++; + return Token::make (LEFT_CURLY, loc); + case '}': + current_column++; + return Token::make (RIGHT_CURLY, loc); + case '@': + current_column++; + return Token::make (PATTERN_BIND, loc); + case '$': + current_column++; + return Token::make (DOLLAR_SIGN, loc); + case '~': + current_column++; + return Token::make (TILDE, loc); + case '\\': + current_column++; + return Token::make (BACKSLASH, loc); + case '`': + current_column++; + return Token::make (BACKTICK, loc); + case '|': + if (peek_input () == '=') + { + // bitwise or-assign? + skip_input (); + current_column += 2; + + return Token::make (PIPE_EQ, loc); + } + else if (peek_input () == '|') + { + // logical or + skip_input (); + current_column += 2; + + return Token::make (OR, loc); + } + else + { + // bitwise or + current_column++; + + return Token::make (PIPE, loc); + } + case '&': + if (peek_input () == '=') + { + // bitwise and-assign? + skip_input (); + current_column += 2; + + return Token::make (AMP_EQ, loc); + } + else if (peek_input () == '&') + { + // logical and + skip_input (); + current_column += 2; + + return Token::make (LOGICAL_AND, loc); + } + else + { + // bitwise and/reference + current_column++; + + return Token::make (AMP, loc); + } + case '.': + if (peek_input () == '.') + { + if (peek_input (1) == '.') + { + // ellipsis + skip_input (1); + current_column += 3; + + return Token::make (ELLIPSIS, loc); + } + else if (peek_input (1) == '=') + { + // ..= + skip_input (1); + current_column += 3; + + return Token::make (DOT_DOT_EQ, loc); + } + else + { + // .. + skip_input (); + current_column += 2; + + return Token::make (DOT_DOT, loc); + } + } + else /*if (!ISDIGIT (peek_input ()))*/ + { + // single dot . + // Only if followed by a non-number - otherwise is float + // nope, float cannot start with '.'. + current_column++; + return Token::make (DOT, loc); + } + } + // TODO: special handling of _ in the lexer? instead of being identifier + + // byte character, byte string and raw byte string literals + if (current_char == 'b') + { + if (peek_input () == '\'') + return parse_byte_char (loc); + else if (peek_input () == '"') + return parse_byte_string (loc); + else if (peek_input () == 'r' + && (peek_input (1) == '#' || peek_input (1) == '"')) + return parse_raw_byte_string (loc); + } + + // raw identifiers and raw strings + if (current_char == 'r') + { + int peek = peek_input (); + int peek1 = peek_input (1); + + if (peek == '#' && (ISALPHA (peek1) || peek1 == '_')) + { + TokenPtr raw_ident_ptr = parse_raw_identifier (loc); + if (raw_ident_ptr != nullptr) + return raw_ident_ptr; + else + continue; /* input got parsed, it just wasn't valid. An error + was produced. */ + } + else + { + TokenPtr maybe_raw_string_ptr = maybe_parse_raw_string (loc); + if (maybe_raw_string_ptr != nullptr) + return maybe_raw_string_ptr; + } + } + + // find identifiers and keywords + if (ISALPHA (current_char) || current_char == '_') + return parse_identifier_or_keyword (loc); + + // int and float literals + if (ISDIGIT (current_char)) + { // _ not allowed as first char + if (current_char == '0' + && is_non_decimal_int_literal_separator (peek_input ())) + { + // handle binary, octal, hex literals + TokenPtr non_dec_int_lit_ptr + = parse_non_decimal_int_literals (loc); + if (non_dec_int_lit_ptr != nullptr) + return non_dec_int_lit_ptr; + } + else + { + // handle decimals (integer or float) + TokenPtr decimal_or_float_ptr = parse_decimal_int_or_float (loc); + if (decimal_or_float_ptr != nullptr) + return decimal_or_float_ptr; + } + } + + // string literals + if (current_char == '"') + return parse_string (loc); + + // char literals and lifetime names + if (current_char == '\'') + { + TokenPtr char_or_lifetime_ptr = parse_char_or_lifetime (loc); + if (char_or_lifetime_ptr != nullptr) + return char_or_lifetime_ptr; + } + + // DEBUG: check for specific character problems: + if (current_char == '0') + rust_debug ("'0' uncaught before unexpected character"); + else if (current_char == ']') + rust_debug ("']' uncaught before unexpected character"); + else if (current_char == 0x5d) + rust_debug ("whatever 0x5d is (not '0' or ']') uncaught before " + "unexpected character"); + + // didn't match anything so error + rust_error_at (loc, "unexpected character %<%x%>", current_char); + current_column++; + } +} + +// Parses in a type suffix. +std::pair +Lexer::parse_in_type_suffix () +{ + std::string suffix; + suffix.reserve (5); + + int additional_length_offset = 0; + + // get suffix + while (ISALPHA (current_char) || ISDIGIT (current_char) + || current_char == '_') + { + if (current_char == '_') + { + // don't add _ to suffix + skip_input (); + current_char = peek_input (); + + additional_length_offset++; + + continue; + } + + additional_length_offset++; + + suffix += current_char; + skip_input (); + current_char = peek_input (); + } + + if (suffix.empty ()) + { + // no type suffix: do nothing but also no error + return std::make_pair (CORETYPE_UNKNOWN, additional_length_offset); + } + else if (suffix == "f32") + { + return std::make_pair (CORETYPE_F32, additional_length_offset); + } + else if (suffix == "f64") + { + return std::make_pair (CORETYPE_F64, additional_length_offset); + } + else if (suffix == "i8") + { + return std::make_pair (CORETYPE_I8, additional_length_offset); + } + else if (suffix == "i16") + { + return std::make_pair (CORETYPE_I16, additional_length_offset); + } + else if (suffix == "i32") + { + return std::make_pair (CORETYPE_I32, additional_length_offset); + } + else if (suffix == "i64") + { + return std::make_pair (CORETYPE_I64, additional_length_offset); + } + else if (suffix == "i128") + { + return std::make_pair (CORETYPE_I128, additional_length_offset); + } + else if (suffix == "isize") + { + return std::make_pair (CORETYPE_ISIZE, additional_length_offset); + } + else if (suffix == "u8") + { + return std::make_pair (CORETYPE_U8, additional_length_offset); + } + else if (suffix == "u16") + { + return std::make_pair (CORETYPE_U16, additional_length_offset); + } + else if (suffix == "u32") + { + return std::make_pair (CORETYPE_U32, additional_length_offset); + } + else if (suffix == "u64") + { + return std::make_pair (CORETYPE_U64, additional_length_offset); + } + else if (suffix == "u128") + { + return std::make_pair (CORETYPE_U128, additional_length_offset); + } + else if (suffix == "usize") + { + return std::make_pair (CORETYPE_USIZE, additional_length_offset); + } + else + { + rust_error_at (get_current_location (), "unknown number suffix %qs", + suffix.c_str ()); + + return std::make_pair (CORETYPE_UNKNOWN, additional_length_offset); + } +} + +// Parses in the exponent part (if any) of a float literal. +std::pair +Lexer::parse_in_exponent_part () +{ + int additional_length_offset = 0; + std::string str; + if (current_char == 'E' || current_char == 'e') + { + // add exponent to string as strtod works with it + str += current_char; + skip_input (); + current_char = peek_input (); + + additional_length_offset++; + + // special - and + handling + if (current_char == '-') + { + str += '-'; + + skip_input (); + current_char = peek_input (); + + additional_length_offset++; + } + else if (current_char == '+') + { + // don't add + but still skip input + skip_input (); + current_char = peek_input (); + + additional_length_offset++; + } + + // parse another decimal number for exponent + auto str_length = parse_in_decimal (); + str += std::get<0> (str_length); + additional_length_offset += std::get<1> (str_length); + } + return std::make_pair (str, additional_length_offset); +} + +// Parses a decimal integer. +std::tuple +Lexer::parse_in_decimal () +{ + /* A pure decimal contains only digits. */ + bool pure_decimal = true; + int additional_length_offset = 0; + std::string str; + while (ISDIGIT (current_char) || current_char == '_') + { + if (current_char == '_') + { + pure_decimal = false; + // don't add _ to number + skip_input (); + current_char = peek_input (); + + additional_length_offset++; + + continue; + } + + additional_length_offset++; + + str += current_char; + skip_input (); + current_char = peek_input (); + } + return std::make_tuple (str, additional_length_offset, pure_decimal); +} + +/* Parses escapes (and string continues) in "byte" strings and characters. Does + * not support unicode. */ +std::tuple +Lexer::parse_escape (char opening_char) +{ + int additional_length_offset = 0; + char output_char = 0; + + // skip to actual letter + skip_input (); + current_char = peek_input (); + additional_length_offset++; + + switch (current_char) + { + case 'x': { + auto hex_escape_pair = parse_partial_hex_escape (); + long hexLong = hex_escape_pair.first; + additional_length_offset += hex_escape_pair.second; + + if (hexLong > 255 || hexLong < 0) + rust_error_at ( + get_current_location (), + "byte \\x escape %<\\x%x%> out of range - allows up to %<\\xFF%>", + static_cast (hexLong)); + /* TODO: restore capital for escape output - gcc pretty-printer doesn't + * support %X directly */ + char hexChar = static_cast (hexLong); + + output_char = hexChar; + } + break; + case 'n': + output_char = '\n'; + break; + case 'r': + output_char = '\r'; + break; + case 't': + output_char = '\t'; + break; + case '\\': + output_char = '\\'; + break; + case '0': + output_char = '\0'; + break; + case '\'': + output_char = '\''; + break; + case '"': + output_char = '"'; + break; + case 'u': + rust_error_at (get_current_location (), + "cannot have a unicode escape \\u in a byte %s", + opening_char == '\'' ? "character" : "string"); + // Try to parse it anyway, just to skip it + parse_partial_unicode_escape (); + return std::make_tuple (output_char, additional_length_offset, false); + case '\r': + case '\n': + // string continue + return std::make_tuple (0, parse_partial_string_continue (), true); + default: + rust_error_at (get_current_location (), + "unknown escape sequence %<\\%c%>", current_char); + // returns false if no parsing could be done + // return false; + return std::make_tuple (output_char, additional_length_offset, false); + break; + } + // all non-special cases (string continue) should skip their used char + skip_input (); + current_char = peek_input (); + additional_length_offset++; + + // returns true if parsing was successful + // return true; + return std::make_tuple (output_char, additional_length_offset, false); +} + +/* Parses an escape (or string continue) in a string or character. Supports + * unicode escapes. */ +std::tuple +Lexer::parse_utf8_escape (char opening_char) +{ + Codepoint output_char; + int additional_length_offset = 0; + + // skip to actual letter + skip_input (); + current_char = peek_input (); + additional_length_offset++; + + switch (current_char) + { + case 'x': { + auto hex_escape_pair = parse_partial_hex_escape (); + long hexLong = hex_escape_pair.first; + additional_length_offset += hex_escape_pair.second; + + if (hexLong > 127 || hexLong < 0) + rust_error_at ( + get_current_location (), + "ascii \\x escape %<\\x%x%> out of range - allows up to %<\\x7F%>", + static_cast (hexLong)); + /* TODO: restore capital for escape output - gcc pretty-printer doesn't + * support %X directly */ + char hexChar = static_cast (hexLong); + + output_char = hexChar; + } + break; + case 'n': + output_char = '\n'; + break; + case 'r': + output_char = '\r'; + break; + case 't': + output_char = '\t'; + break; + case '\\': + output_char = '\\'; + break; + case '0': + output_char = '\0'; + break; + case '\'': + output_char = '\''; + break; + case '"': + output_char = '"'; + break; + case 'u': { + auto unicode_escape_pair = parse_partial_unicode_escape (); + output_char = unicode_escape_pair.first; + additional_length_offset += unicode_escape_pair.second; + + return std::make_tuple (output_char, additional_length_offset, false); + } + break; + case '\r': + case '\n': + // string continue + return std::make_tuple (0, parse_partial_string_continue (), true); + default: + rust_error_at (get_current_location (), + "unknown escape sequence %<\\%c%>", current_char); + // returns false if no parsing could be done + // return false; + return std::make_tuple (output_char, additional_length_offset, false); + break; + } + /* all non-special cases (unicode, string continue) should skip their used + * char */ + skip_input (); + current_char = peek_input (); + additional_length_offset++; + + // returns true if parsing was successful + // return true; + return std::make_tuple (output_char, additional_length_offset, false); +} + +// Parses the body of a string continue that has been found in an escape. +int +Lexer::parse_partial_string_continue () +{ + int additional_length_offset = 1; + + // string continue + while (is_whitespace (current_char)) + { + if (current_char == '\n') + { + current_line++; + current_column = 1; + // tell line_table that new line starts + start_line (current_line, max_column_hint); + + // reset "length" + additional_length_offset = 1; + + // get next char + skip_input (); + current_char = peek_input (); + + continue; + } + + skip_input (); + current_char = peek_input (); + additional_length_offset++; + } + + return additional_length_offset; +} + +/* Parses the body of a '\x' escape. Note that it does not check that the number + * is valid and smaller than 255. */ +std::pair +Lexer::parse_partial_hex_escape () +{ + // hex char string (null-terminated) + char hexNum[3] = {0, 0, 0}; + + // first hex char + current_char = peek_input (1); + int additional_length_offset = 1; + + if (!is_x_digit (current_char)) + { + rust_error_at (get_current_location (), + "invalid character %<\\x%c%> in \\x sequence", + current_char); + return std::make_pair (0, 0); + } + hexNum[0] = current_char; + + // second hex char + skip_input (); + current_char = peek_input (1); + additional_length_offset++; + + if (!is_x_digit (current_char)) + { + rust_error_at (get_current_location (), + "invalid character %<\\x%c%c%> in \\x sequence", hexNum[0], + current_char); + return std::make_pair (0, 1); + } + skip_input (); + hexNum[1] = current_char; + + long hexLong = std::strtol (hexNum, nullptr, 16); + + return std::make_pair (hexLong, additional_length_offset); +} + +// Parses the body of a unicode escape. +std::pair +Lexer::parse_partial_unicode_escape () +{ + skip_input (); + current_char = peek_input (); + int additional_length_offset = 0; + + if (current_char != '{') + { + rust_error_at (get_current_location (), + "unicode escape should start with %<{%>"); + /* Skip what should probaby have been between brackets. */ + while (is_x_digit (current_char) || current_char == '_') + { + skip_input (); + current_char = peek_input (); + additional_length_offset++; + } + return std::make_pair (Codepoint (0), additional_length_offset); + } + + skip_input (); + current_char = peek_input (); + additional_length_offset++; + + if (current_char == '_') + { + rust_error_at (get_current_location (), + "unicode escape cannot start with %<_%>"); + skip_input (); + current_char = peek_input (); + additional_length_offset++; + // fallthrough and try to parse the rest anyway + } + + // parse unicode escape - 1-6 hex digits + std::string num_str; + num_str.reserve (6); + + // loop through to add entire hex number to string + while (is_x_digit (current_char) || current_char == '_') + { + if (current_char == '_') + { + // don't add _ to number + skip_input (); + current_char = peek_input (); + + additional_length_offset++; + + continue; + } + + additional_length_offset++; + + // add raw hex numbers + num_str += current_char; + + skip_input (); + current_char = peek_input (); + } + + if (current_char == '}') + { + skip_input (); + current_char = peek_input (); + additional_length_offset++; + } + else + { + // actually an error, but allow propagation anyway Assume that + // wrong bracketm whitespace or single/double quotes are wrong + // termination, otherwise it is a wrong character, then skip to the actual + // terminator. + if (current_char == '{' || is_whitespace (current_char) + || current_char == '\'' || current_char == '"') + { + rust_error_at (get_current_location (), + "expected terminating %<}%> in unicode escape"); + return std::make_pair (Codepoint (0), additional_length_offset); + } + else + { + rust_error_at (get_current_location (), + "invalid character %<%c%> in unicode escape", + current_char); + while (current_char != '}' && current_char != '{' + && !is_whitespace (current_char) && current_char != '\'' + && current_char != '"') + { + skip_input (); + current_char = peek_input (); + additional_length_offset++; + } + // Consume the actual closing bracket if found + if (current_char == '}') + { + skip_input (); + current_char = peek_input (); + additional_length_offset++; + } + return std::make_pair (Codepoint (0), additional_length_offset); + } + } + + // ensure 1-6 hex characters + if (num_str.length () > 6 || num_str.length () < 1) + { + rust_error_at (get_current_location (), + "unicode escape should be between 1 and 6 hex " + "characters; it is %lu", + (unsigned long) num_str.length ()); + // return false; + return std::make_pair (Codepoint (0), additional_length_offset); + } + + unsigned long hex_num = std::strtoul (num_str.c_str (), nullptr, 16); + + if (hex_num > 0xd7ff && hex_num < 0xe000) + { + rust_error_at ( + get_current_location (), + "unicode escape cannot be a surrogate value (D800 to DFFF)"); + return std::make_pair (Codepoint (0), additional_length_offset); + } + + if (hex_num > 0x10ffff) + { + rust_error_at (get_current_location (), + "unicode escape cannot be larger than 10FFFF"); + return std::make_pair (Codepoint (0), additional_length_offset); + } + + // return true; + return std::make_pair (Codepoint (static_cast (hex_num)), + additional_length_offset); +} + +// Parses a byte character. +TokenPtr +Lexer::parse_byte_char (Location loc) +{ + skip_input (); + current_column++; + // make current char the next character + current_char = peek_input (); + + int length = 1; + + // char to save + char byte_char = 0; + + // detect escapes + if (current_char == '\\') + { + auto escape_length_pair = parse_escape ('\''); + byte_char = std::get<0> (escape_length_pair); + length += std::get<1> (escape_length_pair); + + current_char = peek_input (); + + if (current_char != '\'') + { + rust_error_at (get_current_location (), "unclosed %"); + } + + skip_input (); + current_char = peek_input (); + length++; // go to next char + } + else if (current_char != '\'') + { + // otherwise, get character from direct input character + byte_char = current_char; + + skip_input (); + current_char = peek_input (); + length++; + + if (current_char != '\'') + { + rust_error_at (get_current_location (), "unclosed %"); + } + + skip_input (); + current_char = peek_input (); + length++; // go to next char + } + else + { + rust_error_at (get_current_location (), + "no character inside %<%> for %"); + } + + current_column += length; + + return Token::make_byte_char (loc, byte_char); +} + +// Parses a byte string. +TokenPtr +Lexer::parse_byte_string (Location loc) +{ + // byte string + + // skip quote character + skip_input (); + current_column++; + + std::string str; + str.reserve (16); // some sensible default + + int length = 1; + current_char = peek_input (); + + while (current_char != '"' && current_char != EOF) + { + if (current_char == '\\') + { + auto escape_length_pair = parse_escape ('"'); + char output_char = std::get<0> (escape_length_pair); + + if (output_char == 0 && std::get<2> (escape_length_pair)) + length = std::get<1> (escape_length_pair) - 1; + else + length += std::get<1> (escape_length_pair); + + if (output_char != 0 || !std::get<2> (escape_length_pair)) + str += output_char; + + continue; + } + + length++; + + str += current_char; + skip_input (); + current_char = peek_input (); + } + + current_column += length; + + if (current_char == '"') + { + current_column++; + + skip_input (); + current_char = peek_input (); + } + else if (current_char == EOF) + { + rust_error_at (get_current_location (), "unended byte string literal"); + return Token::make (END_OF_FILE, get_current_location ()); + } + else + { + gcc_unreachable (); + } + + str.shrink_to_fit (); + + return Token::make_byte_string (loc, std::move (str)); +} + +// Parses a raw byte string. +TokenPtr +Lexer::parse_raw_byte_string (Location loc) +{ + // raw byte string literals + std::string str; + str.reserve (16); // some sensible default + + int length = 1; + int hash_count = 0; + + // get hash count at beginnning + skip_input (); + current_char = peek_input (); + length++; + while (current_char == '#') + { + hash_count++; + length++; + + skip_input (); + current_char = peek_input (); + } + + if (current_char != '"') + { + rust_error_at (get_current_location (), + "raw byte string has no opening %<\"%>"); + } + + skip_input (); + current_char = peek_input (); + length++; + + while (true) + { + if (current_char == '"') + { + bool enough_hashes = true; + + for (int i = 0; i < hash_count; i++) + { + if (peek_input (i + 1) != '#') + { + enough_hashes = false; + break; + } + } + + if (enough_hashes) + { + // skip enough input and peek enough input + skip_input (hash_count); + current_char = peek_input (); + length += hash_count + 1; + break; + } + } + + if ((unsigned char) current_char > 127) + { + rust_error_at (get_current_location (), + "character %<%c%> in raw byte string out of range", + current_char); + current_char = 0; + } + + length++; + + str += current_char; + skip_input (); + current_char = peek_input (); + } + + current_column += length; + + str.shrink_to_fit (); + + return Token::make_byte_string (loc, std::move (str)); +} + +// Parses a raw identifier. +TokenPtr +Lexer::parse_raw_identifier (Location loc) +{ + // raw identifier + std::string str; + str.reserve (16); // default + + skip_input (); + current_char = peek_input (); + + current_column += 2; + + bool first_is_underscore = current_char == '_'; + + int length = 0; + current_char = peek_input (); + // loop through entire name + while (ISALPHA (current_char) || ISDIGIT (current_char) + || current_char == '_') + { + length++; + + str += current_char; + skip_input (); + current_char = peek_input (); + } + + current_column += length; + + // if just a single underscore, not an identifier + if (first_is_underscore && length == 1) + rust_error_at (get_current_location (), + "%<_%> is not a valid raw identifier"); + + if (str == "crate" || str == "extern" || str == "self" || str == "super" + || str == "Self") + { + rust_error_at (get_current_location (), + "%qs is a forbidden raw identifier", str.c_str ()); + + return nullptr; + } + else + { + str.shrink_to_fit (); + + return Token::make_identifier (loc, std::move (str)); + } +} + +// skip broken string input (unterminated strings) +void +Lexer::skip_broken_string_input (int current_char) +{ + while (current_char != '"' && current_char != EOF) + { + if (current_char == '\n') + { + current_line++; + current_column = 1; + } + else + { + current_column++; + } + skip_input (); + current_char = peek_input (); + } + if (current_char == '"') + { + current_column++; + + skip_input (); + current_char = peek_input (); + } + rust_debug ("skipped to %d:%d due to bad quotes", current_line, + current_column); +} + +// Parses a unicode string. +TokenPtr +Lexer::parse_string (Location loc) +{ + Codepoint current_char32; + + std::string str; + str.reserve (16); // some sensible default + + int length = 1; + current_char32 = peek_codepoint_input (); + + // FIXME: This fails if the input ends. How do we check for EOF? + while (current_char32.value != '"' && !current_char32.is_eof ()) + { + if (current_char32.value == '\\') + { + // parse escape + auto utf8_escape_pair = parse_utf8_escape ('\''); + current_char32 = std::get<0> (utf8_escape_pair); + + if (current_char32 == Codepoint (0) && std::get<2> (utf8_escape_pair)) + length = std::get<1> (utf8_escape_pair) - 1; + else + length += std::get<1> (utf8_escape_pair); + + if (current_char32 != Codepoint (0) + || !std::get<2> (utf8_escape_pair)) + str += current_char32; + + // required as parsing utf8 escape only changes current_char + current_char32 = peek_codepoint_input (); + + continue; + } + + length += get_input_codepoint_length (); + + str += current_char32; + skip_codepoint_input (); + current_char32 = peek_codepoint_input (); + } + + current_column += length; + + if (current_char32.value == '"') + { + current_column++; + + skip_input (); + current_char = peek_input (); + } + else if (current_char32.is_eof ()) + { + rust_error_at (get_current_location (), "unended string literal"); + return Token::make (END_OF_FILE, get_current_location ()); + } + else + { + gcc_unreachable (); + } + + str.shrink_to_fit (); + return Token::make_string (loc, std::move (str)); +} + +// Parses an identifier or keyword. +TokenPtr +Lexer::parse_identifier_or_keyword (Location loc) +{ + std::string str; + str.reserve (16); // default + str += current_char; + + bool first_is_underscore = current_char == '_'; + + int length = 1; + current_char = peek_input (); + // loop through entire name + while (ISALPHA (current_char) || ISDIGIT (current_char) + || current_char == '_') + { + length++; + + str += current_char; + skip_input (); + current_char = peek_input (); + } + + current_column += length; + + // if just a single underscore, not an identifier + if (first_is_underscore && length == 1) + return Token::make (UNDERSCORE, loc); + + str.shrink_to_fit (); + + TokenId keyword = classify_keyword (str); + if (keyword == IDENTIFIER) + return Token::make_identifier (loc, std::move (str)); + else + return Token::make (keyword, loc); +} + +// Possibly returns a raw string token if it exists - otherwise returns null. +TokenPtr +Lexer::maybe_parse_raw_string (Location loc) +{ + int peek_index = 0; + while (peek_input (peek_index) == '#') + peek_index++; + + if (peek_input (peek_index) == '"') + return parse_raw_string (loc, peek_index); + else + return nullptr; +} + +// Returns a raw string token. +TokenPtr +Lexer::parse_raw_string (Location loc, int initial_hash_count) +{ + // raw string literals + std::string str; + str.reserve (16); // some sensible default + + int length = 1 + initial_hash_count; + + if (initial_hash_count > 0) + skip_input (initial_hash_count - 1); + + current_char = peek_input (); + + if (current_char != '"') + rust_error_at (get_current_location (), "raw string has no opening %<\"%>"); + + length++; + skip_input (); + Codepoint current_char32 = peek_codepoint_input (); + + while (!current_char32.is_eof ()) + { + if (current_char32.value == '"') + { + bool enough_hashes = true; + + for (int i = 0; i < initial_hash_count; i++) + { + if (peek_input (i + 1) != '#') + { + enough_hashes = false; + break; + } + } + + if (enough_hashes) + { + // skip enough input and peek enough input + skip_input (initial_hash_count); + current_char = peek_input (); + length += initial_hash_count + 1; + break; + } + } + + length++; + + str += current_char32; + skip_codepoint_input (); + current_char32 = peek_codepoint_input (); + } + + current_column += length; + + str.shrink_to_fit (); + + return Token::make_string (loc, std::move (str)); +} + +template +TokenPtr +Lexer::parse_non_decimal_int_literal (Location loc, IsDigitFunc is_digit_func, + std::string existent_str, int base) +{ + int length = 1; + + skip_input (); + current_char = peek_input (); + + length++; + + // loop through to add entire number to string + while (is_digit_func (current_char) || current_char == '_') + { + if (current_char == '_') + { + // don't add _ to number + skip_input (); + current_char = peek_input (); + + length++; + + continue; + } + + length++; + + // add raw numbers + existent_str += current_char; + skip_input (); + current_char = peek_input (); + } + + // convert value to decimal representation + long dec_num = std::strtol (existent_str.c_str (), nullptr, base); + + existent_str = std::to_string (dec_num); + + // parse in type suffix if it exists + auto type_suffix_pair = parse_in_type_suffix (); + PrimitiveCoreType type_hint = type_suffix_pair.first; + length += type_suffix_pair.second; + + current_column += length; + + if (type_hint == CORETYPE_F32 || type_hint == CORETYPE_F64) + { + rust_error_at (get_current_location (), + "invalid type suffix %qs for integer (%s) literal", + get_type_hint_string (type_hint), + base == 16 + ? "hex" + : (base == 8 ? "octal" + : (base == 2 ? "binary" + : ""))); + return nullptr; + } + return Token::make_int (loc, std::move (existent_str), type_hint); +} + +// Parses a hex, binary or octal int literal. +TokenPtr +Lexer::parse_non_decimal_int_literals (Location loc) +{ + std::string str; + str.reserve (16); // some sensible default + str += current_char; + + current_char = peek_input (); + + if (current_char == 'x') + { + // hex (integer only) + return parse_non_decimal_int_literal (loc, is_x_digit, str + "x", 16); + } + else if (current_char == 'o') + { + // octal (integer only) + return parse_non_decimal_int_literal (loc, is_octal_digit, + std::move (str), 8); + } + else if (current_char == 'b') + { + // binary (integer only) + return parse_non_decimal_int_literal (loc, is_bin_digit, std::move (str), + 2); + } + else + { + return nullptr; + } +} + +// Parses a decimal-based int literal or float literal. +TokenPtr +Lexer::parse_decimal_int_or_float (Location loc) +{ + std::string str; + str.reserve (16); // some sensible default + str += current_char; + + int length = 1; + bool first_zero = current_char == '0'; + + current_char = peek_input (); + + // parse initial decimal integer (or first integer part of float) literal + auto initial_decimal = parse_in_decimal (); + str += std::get<0> (initial_decimal); + length += std::get<1> (initial_decimal); + + // detect float literal + if (current_char == '.' && is_float_digit (peek_input (1))) + { + // float with a '.', parse another decimal into it + + // add . to str + str += current_char; + skip_input (); + current_char = peek_input (); + length++; + + // parse another decimal number for float + auto second_decimal = parse_in_decimal (); + str += std::get<0> (second_decimal); + length += std::get<1> (second_decimal); + + // parse in exponent part if it exists + auto exponent_pair = parse_in_exponent_part (); + str += exponent_pair.first; + length += exponent_pair.second; + + // parse in type suffix if it exists + auto type_suffix_pair = parse_in_type_suffix (); + PrimitiveCoreType type_hint = type_suffix_pair.first; + length += type_suffix_pair.second; + + if (type_hint != CORETYPE_F32 && type_hint != CORETYPE_F64 + && type_hint != CORETYPE_UNKNOWN) + { + rust_error_at (get_current_location (), + "invalid type suffix %qs for floating-point literal", + get_type_hint_string (type_hint)); + // ignore invalid type suffix as everything else seems fine + type_hint = CORETYPE_UNKNOWN; + } + + current_column += length; + + str.shrink_to_fit (); + return Token::make_float (loc, std::move (str), type_hint); + } + else if (current_char == '.' && check_valid_float_dot_end (peek_input (1))) + { + // float that is just an integer with a terminating '.' character + + // add . to str + str += current_char; + skip_input (); + current_char = peek_input (); + length++; + + // add a '0' after the . to prevent ambiguity + str += '0'; + + // type hint not allowed + + current_column += length; + + str.shrink_to_fit (); + return Token::make_float (loc, std::move (str), CORETYPE_UNKNOWN); + } + else if (current_char == 'E' || current_char == 'e') + { + // exponent float with no '.' character + + // parse exponent part + auto exponent_pair = parse_in_exponent_part (); + str += exponent_pair.first; + length += exponent_pair.second; + + // parse in type suffix if it exists + auto type_suffix_pair = parse_in_type_suffix (); + PrimitiveCoreType type_hint = type_suffix_pair.first; + length += type_suffix_pair.second; + + if (type_hint != CORETYPE_F32 && type_hint != CORETYPE_F64 + && type_hint != CORETYPE_UNKNOWN) + { + rust_error_at (get_current_location (), + "invalid type suffix %qs for floating-point literal", + get_type_hint_string (type_hint)); + // ignore invalid type suffix as everything else seems fine + type_hint = CORETYPE_UNKNOWN; + } + + current_column += length; + + str.shrink_to_fit (); + return Token::make_float (loc, std::move (str), type_hint); + } + else + { + // is an integer + + // parse in type suffix if it exists + auto type_suffix_pair = parse_in_type_suffix (); + PrimitiveCoreType type_hint = type_suffix_pair.first; + /* A "real" pure decimal doesn't have a suffix and no zero prefix. */ + if (type_hint == CORETYPE_UNKNOWN) + { + bool pure_decimal = std::get<2> (initial_decimal); + if (pure_decimal && (!first_zero || str.size () == 1)) + type_hint = CORETYPE_PURE_DECIMAL; + } + length += type_suffix_pair.second; + + current_column += length; + + str.shrink_to_fit (); + return Token::make_int (loc, std::move (str), type_hint); + } +} + +TokenPtr +Lexer::parse_char_or_lifetime (Location loc) +{ + Codepoint current_char32; + + int length = 1; + + current_char32 = peek_codepoint_input (); + if (current_char32.is_eof ()) + return nullptr; + + // parse escaped char literal + if (current_char32.value == '\\') + { + // parse escape + auto utf8_escape_pair = parse_utf8_escape ('\''); + current_char32 = std::get<0> (utf8_escape_pair); + length += std::get<1> (utf8_escape_pair); + + if (peek_codepoint_input ().value != '\'') + { + rust_error_at (get_current_location (), "unended character literal"); + } + else + { + skip_codepoint_input (); + current_char = peek_input (); + length++; + } + + current_column += length; + + return Token::make_char (loc, current_char32); + } + else + { + skip_codepoint_input (); + + if (peek_codepoint_input ().value == '\'') + { + // parse non-escaped char literal + + // skip the ' character + skip_input (); + current_char = peek_input (); + + // TODO fix due to different widths of utf-8 chars? + current_column += 3; + + return Token::make_char (loc, current_char32); + } + else if (ISDIGIT (current_char32.value) || ISALPHA (current_char32.value) + || current_char32.value == '_') + { + // parse lifetime name + std::string str; + str += current_char32; + length++; + + current_char = peek_input (); + while (ISDIGIT (current_char) || ISALPHA (current_char) + || current_char == '_') + { + str += current_char; + skip_input (); + current_char = peek_input (); + length++; + } + + current_column += length; + + str.shrink_to_fit (); + return Token::make_lifetime (loc, std::move (str)); + } + else + { + rust_error_at ( + get_current_location (), + "expected %' after character constant in character literal"); + return nullptr; + } + } +} + +// Returns the length of the codepoint at the current position. +int +Lexer::get_input_codepoint_length () +{ + uint8_t input = peek_input (); + + if ((int8_t) input == EOF) + return 0; + + if (input < 128) + { + // ascii -- 1 byte + // return input; + + return 1; + } + else if ((input & 0xC0) == 0x80) + { + // invalid (continuation; can't be first char) + // return 0xFFFE; + + return 0; + } + else if ((input & 0xE0) == 0xC0) + { + // 2 bytes + uint8_t input2 = peek_input (1); + if ((input2 & 0xC0) != 0x80) + return 0; + // return 0xFFFE; + + // uint32_t output = ((input & 0x1F) << 6) | ((input2 & 0x3F) << 0); + // return output; + return 2; + } + else if ((input & 0xF0) == 0xE0) + { + // 3 bytes + uint8_t input2 = peek_input (1); + if ((input2 & 0xC0) != 0x80) + return 0; + // return 0xFFFE; + + uint8_t input3 = peek_input (2); + if ((input3 & 0xC0) != 0x80) + return 0; + // return 0xFFFE; + + /*uint32_t output + = ((input & 0x0F) << 12) | ((input2 & 0x3F) << 6) | ((input3 & 0x3F) << + 0); return output;*/ + return 3; + } + else if ((input & 0xF8) == 0xF0) + { + // 4 bytes + uint8_t input2 = peek_input (1); + if ((input2 & 0xC0) != 0x80) + return 0; + // return 0xFFFE; + + uint8_t input3 = peek_input (2); + if ((input3 & 0xC0) != 0x80) + return 0; + // return 0xFFFE; + + uint8_t input4 = peek_input (3); + if ((input4 & 0xC0) != 0x80) + return 0; + // return 0xFFFE; + + /*uint32_t output = ((input & 0x07) << 18) | ((input2 & 0x3F) << 12) + | ((input3 & 0x3F) << 6) | ((input4 & 0x3F) << 0); + return output;*/ + return 4; + } + else + { + rust_error_at (get_current_location (), + "invalid UTF-8 [FIRST] (too long)"); + return 0; + } +} + +// Returns the codepoint at the current position. +Codepoint +Lexer::peek_codepoint_input () +{ + uint8_t input = peek_input (); + + if ((int8_t) input == EOF) + return Codepoint::eof (); + + if (input < 128) + { + // ascii -- 1 byte + return {input}; + } + else if ((input & 0xC0) == 0x80) + { + // invalid (continuation; can't be first char) + return {0xFFFE}; + } + else if ((input & 0xE0) == 0xC0) + { + // 2 bytes + uint8_t input2 = peek_input (1); + if ((input2 & 0xC0) != 0x80) + return {0xFFFE}; + + uint32_t output = ((input & 0x1F) << 6) | ((input2 & 0x3F) << 0); + return {output}; + } + else if ((input & 0xF0) == 0xE0) + { + // 3 bytes + uint8_t input2 = peek_input (1); + if ((input2 & 0xC0) != 0x80) + return {0xFFFE}; + + uint8_t input3 = peek_input (2); + if ((input3 & 0xC0) != 0x80) + return {0xFFFE}; + + uint32_t output = ((input & 0x0F) << 12) | ((input2 & 0x3F) << 6) + | ((input3 & 0x3F) << 0); + return {output}; + } + else if ((input & 0xF8) == 0xF0) + { + // 4 bytes + uint8_t input2 = peek_input (1); + if ((input2 & 0xC0) != 0x80) + return {0xFFFE}; + + uint8_t input3 = peek_input (2); + if ((input3 & 0xC0) != 0x80) + return {0xFFFE}; + + uint8_t input4 = peek_input (3); + if ((input4 & 0xC0) != 0x80) + return {0xFFFE}; + + uint32_t output = ((input & 0x07) << 18) | ((input2 & 0x3F) << 12) + | ((input3 & 0x3F) << 6) | ((input4 & 0x3F) << 0); + return {output}; + } + else + { + rust_error_at (get_current_location (), + "invalid UTF-8 [SECND] (too long)"); + return {0xFFFE}; + } +} + +void +Lexer::skip_codepoint_input () +{ + int toSkip = get_input_codepoint_length (); + gcc_assert (toSkip >= 1); + + skip_input (toSkip - 1); +} + +int +Lexer::test_get_input_codepoint_n_length (int n_start_offset) +{ + uint8_t input = peek_input (n_start_offset); + + if (input < 128) + { + // ascii -- 1 byte + // return input; + return 1; + } + else if ((input & 0xC0) == 0x80) + { + // invalid (continuation; can't be first char) + // return 0xFFFE; + return 0; + } + else if ((input & 0xE0) == 0xC0) + { + // 2 bytes + uint8_t input2 = peek_input (n_start_offset + 1); + if ((input2 & 0xC0) != 0x80) + // return 0xFFFE; + return 0; + + // uint32_t output = ((input & 0x1F) << 6) | ((input2 & 0x3F) << 0); + // return output; + return 2; + } + else if ((input & 0xF0) == 0xE0) + { + // 3 bytes + uint8_t input2 = peek_input (n_start_offset + 1); + if ((input2 & 0xC0) != 0x80) + // return 0xFFFE; + return 0; + + uint8_t input3 = peek_input (n_start_offset + 2); + if ((input3 & 0xC0) != 0x80) + // return 0xFFFE; + return 0; + + /*uint32_t output + = ((input & 0x0F) << 12) | ((input2 & 0x3F) << 6) | ((input3 & 0x3F) << + 0); return output;*/ + return 3; + } + else if ((input & 0xF8) == 0xF0) + { + // 4 bytes + uint8_t input2 = peek_input (n_start_offset + 1); + if ((input2 & 0xC0) != 0x80) + // return 0xFFFE; + return 0; + + uint8_t input3 = peek_input (n_start_offset + 2); + if ((input3 & 0xC0) != 0x80) + // return 0xFFFE; + return 0; + + uint8_t input4 = peek_input (n_start_offset + 3); + if ((input4 & 0xC0) != 0x80) + // return 0xFFFE; + return 0; + + /*uint32_t output = ((input & 0x07) << 18) | ((input2 & 0x3F) << 12) + | ((input3 & 0x3F) << 6) | ((input4 & 0x3F) << 0); + return output;*/ + return 4; + } + else + { + rust_error_at (get_current_location (), + "invalid UTF-8 [THIRD] (too long)"); + return 0; + } +} + +// peeks the codepoint input at n codepoints ahead of current codepoint - try +// not to use +Codepoint +Lexer::test_peek_codepoint_input (int n) +{ + int totalOffset = 0; + + // add up all offsets into total offset? does this do what I want? + for (int i = 0; i < n; i++) + { + totalOffset += test_get_input_codepoint_n_length (totalOffset); + } + // issues: this would have (at least) O(n) lookup time, not O(1) like the + // rest? + + // TODO: implement if still needed + + // error out of function as it is not implemented + gcc_assert (1 == 0); + return {0}; + /* + uint8_t input = peek_input(); + + if (input < 128) { + // ascii -- 1 byte + return input; + } else if ((input & 0xC0) == 0x80) { + // invalid (continuation; can't be first char) + return 0xFFFE; + } else if ((input & 0xE0) == 0xC0) { + // 2 bytes + uint8_t input2 = peek_input(1); + if ((input2 & 0xC0) != 0x80) + return 0xFFFE; + + uint32_t output = ((input & 0x1F) << 6) | ((input2 & 0x3F) << 0); + return output; + } else if ((input & 0xF0) == 0xE0) { + // 3 bytes + uint8_t input2 = peek_input(1); + if ((input2 & 0xC0) != 0x80) + return 0xFFFE; + + uint8_t input3 = peek_input(2); + if ((input3 & 0xC0) != 0x80) + return 0xFFFE; + + uint32_t output + = ((input & 0x0F) << 12) | ((input2 & 0x3F) << 6) | ((input3 & + 0x3F) << 0); return output; } else if ((input & 0xF8) == 0xF0) { + // 4 bytes + uint8_t input2 = peek_input(1); + if ((input2 & 0xC0) != 0x80) + return 0xFFFE; + + uint8_t input3 = peek_input(2); + if ((input3 & 0xC0) != 0x80) + return 0xFFFE; + + uint8_t input4 = peek_input(3); + if ((input4 & 0xC0) != 0x80) + return 0xFFFE; + + uint32_t output = ((input & 0x07) << 18) | ((input2 & 0x3F) << 12) + | ((input3 & 0x3F) << 6) | ((input4 & 0x3F) << + 0); return output; } else { rust_error_at(get_current_location(), "invalid + UTF-8 (too long)"); return 0xFFFE; + }*/ +} + +void +Lexer::split_current_token (TokenId new_left, TokenId new_right) +{ + /* TODO: assert that this TokenId is a "simple token" like punctuation and not + * like "IDENTIFIER"? */ + Location current_loc = peek_token ()->get_locus (); + TokenPtr new_left_tok = Token::make (new_left, current_loc); + TokenPtr new_right_tok = Token::make (new_right, current_loc + 1); + + token_queue.replace_current_value (std::move (new_left_tok)); + token_queue.insert (1, std::move (new_right_tok)); +} + +void +Lexer::start_line (int current_line, int current_column) +{ + if (line_map) + line_map->start_line (current_line, current_column); +} + +} // namespace Rust diff --git a/gcc/rust/lex/rust-lex.h b/gcc/rust/lex/rust-lex.h new file mode 100644 index 00000000000..d5a6c53719f --- /dev/null +++ b/gcc/rust/lex/rust-lex.h @@ -0,0 +1,271 @@ +// Copyright (C) 2020-2022 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 +// . + +#ifndef RUST_LEX_H +#define RUST_LEX_H + +#include "rust-linemap.h" +#include "rust-buffered-queue.h" +#include "rust-token.h" + +namespace Rust { +// Simple wrapper for FILE* that simplifies destruction. +struct RAIIFile +{ +private: + FILE *file; + const char *filename; + + void close () + { + if (file != nullptr && file != stdin) + fclose (file); + } + +public: + RAIIFile (const char *filename) : filename (filename) + { + if (strcmp (filename, "-") == 0) + file = stdin; + else + file = fopen (filename, "r"); + } + + /** + * Create a RAIIFile from an existing instance of FILE* + */ + RAIIFile (FILE *raw, const char *filename = nullptr) + : file (raw), filename (filename) + {} + + RAIIFile (const RAIIFile &other) = delete; + RAIIFile &operator= (const RAIIFile &other) = delete; + + // have to specify setting file to nullptr, otherwise unintended fclose occurs + RAIIFile (RAIIFile &&other) : file (other.file), filename (other.filename) + { + other.file = nullptr; + } + + RAIIFile &operator= (RAIIFile &&other) + { + close (); + file = other.file; + filename = other.filename; + other.file = nullptr; + + return *this; + } + + static RAIIFile create_error () { return RAIIFile (nullptr, nullptr); } + + ~RAIIFile () { close (); } + + FILE *get_raw () { return file; } + const char *get_filename () { return filename; } + + bool ok () const { return file; } +}; + +class Lexer +{ +private: + // Request new Location for current column in line_table + Location get_current_location (); + + // Skips the current input char. + void skip_input (); + // Advances current input char to n + 1 chars ahead of current position. + void skip_input (int n); + + // Returns char n chars ahead of current position. + int peek_input (); + // Peeks the current char. + int peek_input (int n); + + // Classifies keyword (i.e. gets id for keyword). + TokenId classify_keyword (const std::string &str); + + // Builds a token from the input queue. + TokenPtr build_token (); + + std::tuple parse_in_decimal (); + std::pair parse_in_exponent_part (); + std::pair parse_in_type_suffix (); + std::tuple parse_escape (char opening_char); + std::tuple parse_utf8_escape (char opening_char); + int parse_partial_string_continue (); + std::pair parse_partial_hex_escape (); + std::pair parse_partial_unicode_escape (); + + int get_input_codepoint_length (); + int test_get_input_codepoint_n_length (int n_start_offset); + Codepoint peek_codepoint_input (); + Codepoint test_peek_codepoint_input (int n); + void skip_codepoint_input (); + void skip_broken_string_input (int current_char); + + TokenPtr parse_byte_char (Location loc); + TokenPtr parse_byte_string (Location loc); + TokenPtr parse_raw_byte_string (Location loc); + TokenPtr parse_raw_identifier (Location loc); + TokenPtr parse_string (Location loc); + TokenPtr maybe_parse_raw_string (Location loc); + TokenPtr parse_raw_string (Location loc, int initial_hash_count); + TokenPtr parse_non_decimal_int_literals (Location loc); + TokenPtr parse_decimal_int_or_float (Location loc); + TokenPtr parse_char_or_lifetime (Location loc); + TokenPtr parse_identifier_or_keyword (Location loc); + + template + TokenPtr parse_non_decimal_int_literal (Location loc, + IsDigitFunc is_digit_func, + std::string existent_str, int base); + +public: + // Construct lexer with input file and filename provided + Lexer (const char *filename, RAIIFile input, Linemap *linemap); + + // Lex the contents of a string instead of a file + Lexer (const std::string &input); + + // dtor + ~Lexer (); + + // don't allow copy semantics (for now, at least) + Lexer (const Lexer &other) = delete; + Lexer &operator= (const Lexer &other) = delete; + + // enable move semantics + Lexer (Lexer &&other) = default; + Lexer &operator= (Lexer &&other) = default; + + // Returns token n tokens ahead of current position. + const_TokenPtr peek_token (int n) { return token_queue.peek (n); } + // Peeks the current token. + const_TokenPtr peek_token () { return peek_token (0); } + + // Advances current token to n + 1 tokens ahead of current position. + void skip_token (int n) { token_queue.skip (n); } + // Skips the current token. + void skip_token () { skip_token (0); } + + // Replaces the current token with a specified token. + void replace_current_token (TokenPtr replacement); + // FIXME: don't use anymore + + /* Splits the current token into two. Intended for use with nested generics + * closes (i.e. T> where >> is wrongly lexed as one token). Note that + * this will only work with "simple" tokens like punctuation. */ + void split_current_token (TokenId new_left, TokenId new_right); + + Linemap *get_line_map () { return line_map; } + std::string get_filename () { return std::string (input.get_filename ()); } + +private: + void start_line (int current_line, int current_column); + + // File for use as input. + RAIIFile input; + // TODO is this actually required? could just have file storage in InputSource + + // Current line number. + int current_line; + // Current column number. + int current_column; + // Current character. + int current_char; + // Line map. + Linemap *line_map; + + /* Max column number that can be quickly allocated - higher may require + * allocating new linemap */ + static const int max_column_hint = 80; + + // Input source wrapper thing. + class InputSource + { + public: + virtual ~InputSource () {} + + // Overload operator () to return next char from input stream. + virtual int next () = 0; + }; + + class FileInputSource : public InputSource + { + private: + // Input source file. + FILE *input; + + public: + // Create new input source from file. + FileInputSource (FILE *input) : input (input) {} + + int next () override { return fgetc (input); } + }; + + class BufferInputSource : public InputSource + { + private: + const std::string &buffer; + size_t offs; + + public: + // Create new input source from file. + BufferInputSource (const std::string &b, size_t offset) + : buffer (b), offs (offset) + {} + + int next () override + { + if (offs >= buffer.size ()) + return EOF; + + return buffer.at (offs++); + } + }; + + // The input source for the lexer. + // InputSource input_source; + // Input file queue. + std::unique_ptr raw_input_source; + buffered_queue input_queue; + + // Token source wrapper thing. + struct TokenSource + { + // The lexer object that will use this TokenSource. + Lexer *lexer; + + // Create a new TokenSource with given lexer. + TokenSource (Lexer *parLexer) : lexer (parLexer) {} + + // Overload operator () to build token in lexer. + TokenPtr next () { return lexer->build_token (); } + }; + + // The token source for the lexer. + // TokenSource token_source; + // Token stream queue. + buffered_queue, TokenSource> token_queue; +}; + +} // namespace Rust + +#endif diff --git a/gcc/rust/lex/rust-token.cc b/gcc/rust/lex/rust-token.cc new file mode 100644 index 00000000000..68313c20b1c --- /dev/null +++ b/gcc/rust/lex/rust-token.cc @@ -0,0 +1,135 @@ +// Copyright (C) 2020-2022 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 +// . + +#include "rust-token.h" + +#include "rust-diagnostics.h" // for error_at + +namespace Rust { +// Hackily defined way to get token description for enum value using x-macros +const char * +get_token_description (TokenId id) +{ + switch (id) + { +#define RS_TOKEN(name, descr) \ + case name: \ + return descr; +#define RS_TOKEN_KEYWORD(x, y) RS_TOKEN (x, y) + RS_TOKEN_LIST +#undef RS_TOKEN_KEYWORD +#undef RS_TOKEN + default: + gcc_unreachable (); + } +} + +/* Hackily defined way to get token description as a string for enum value using + * x-macros */ +const char * +token_id_to_str (TokenId id) +{ + switch (id) + { +#define RS_TOKEN(name, _) \ + case name: \ + return #name; +#define RS_TOKEN_KEYWORD(x, y) RS_TOKEN (x, y) + RS_TOKEN_LIST +#undef RS_TOKEN_KEYWORD +#undef RS_TOKEN + default: + gcc_unreachable (); + } +} + +const char * +get_type_hint_string (PrimitiveCoreType type) +{ + switch (type) + { + case CORETYPE_BOOL: + return "bool"; + case CORETYPE_CHAR: + return "char"; + case CORETYPE_STR: + return "str"; + // case CORETYPE_INT: + case CORETYPE_ISIZE: + return "isize"; + // case CORETYPE_UINT: + case CORETYPE_USIZE: + return "usize"; + case CORETYPE_F32: + return "f32"; + case CORETYPE_F64: + return "f64"; + case CORETYPE_I8: + return "i8"; + case CORETYPE_I16: + return "i16"; + case CORETYPE_I32: + return "i32"; + case CORETYPE_I64: + return "i64"; + case CORETYPE_I128: + return "i128"; + case CORETYPE_U8: + return "u8"; + case CORETYPE_U16: + return "u16"; + case CORETYPE_U32: + return "u32"; + case CORETYPE_U64: + return "u64"; + case CORETYPE_U128: + return "u128"; + case CORETYPE_PURE_DECIMAL: + return "pure_decimal"; + case CORETYPE_UNKNOWN: + default: + return "unknown"; + } +} + +const char * +Token::get_type_hint_str () const +{ + return get_type_hint_string (type_hint); +} + +const std::string & +Token::get_str () const +{ + // FIXME: attempt to return null again + // gcc_assert(str != NULL); + + // HACK: allow referencing an empty string + static const std::string empty = ""; + + if (str == NULL) + { + rust_error_at (get_locus (), + "attempted to get string for %<%s%>, which has no string. " + "returning empty string instead", + get_token_description ()); + return empty; + } + return *str; +} +} // namespace Rust diff --git a/gcc/rust/lex/rust-token.h b/gcc/rust/lex/rust-token.h new file mode 100644 index 00000000000..3fa46a2cebe --- /dev/null +++ b/gcc/rust/lex/rust-token.h @@ -0,0 +1,455 @@ +// Copyright (C) 2020-2022 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 +// . + +#ifndef RUST_TOKEN_H +#define RUST_TOKEN_H + +#include "rust-linemap.h" +#include "rust-codepoint.h" + +// order: config, system, coretypes, input +#include "config.h" +#include "system.h" +#include "coretypes.h" +#include "input.h" + +namespace Rust { +// "Primitive core types" in Rust - the different int and float types, as well +// as some others +enum PrimitiveCoreType +{ + CORETYPE_UNKNOWN, + // named primitives + CORETYPE_BOOL, + CORETYPE_CHAR, + CORETYPE_STR, + // okay technically int and uint are arch-dependent (pointer size) + CORETYPE_INT, + CORETYPE_UINT, + // numbered number primitives + CORETYPE_F32, + CORETYPE_F64, + CORETYPE_I8, + CORETYPE_I16, + CORETYPE_I32, + CORETYPE_I64, + CORETYPE_I128, + CORETYPE_U8, + CORETYPE_U16, + CORETYPE_U32, + CORETYPE_U64, + CORETYPE_U128, + // Pure decimals are used for tuple index. + // Also means there is no type hint. + CORETYPE_PURE_DECIMAL, + // arch-dependent pointer sizes + CORETYPE_ISIZE = CORETYPE_INT, + CORETYPE_USIZE = CORETYPE_UINT +}; + +// RS_TOKEN(name, description) +// RS_TOKEN_KEYWORD(name, identifier) +// +// Keep RS_TOKEN_KEYWORD sorted + +/* note that abstract, async, become, box, do, final, macro, override, priv, + * try, typeof, unsized, virtual, and yield are unused */ +#define RS_TOKEN_LIST \ + RS_TOKEN (FIRST_TOKEN, "") \ + RS_TOKEN (END_OF_FILE, "end of file") \ + RS_TOKEN (EXCLAM, "!") \ + RS_TOKEN (NOT_EQUAL, "!=") \ + RS_TOKEN (PERCENT, "%") \ + RS_TOKEN (PERCENT_EQ, "%=") \ + RS_TOKEN (AMP, "&") \ + RS_TOKEN (AMP_EQ, "&=") \ + RS_TOKEN (LOGICAL_AND, "&&") \ + RS_TOKEN (ASTERISK, "*") \ + RS_TOKEN (ASTERISK_EQ, "*=") \ + RS_TOKEN (PLUS, "+") \ + RS_TOKEN (PLUS_EQ, "+=") \ + RS_TOKEN (COMMA, ",") \ + RS_TOKEN (MINUS, "-") \ + RS_TOKEN (MINUS_EQ, "-=") \ + RS_TOKEN (RETURN_TYPE, "->") \ + RS_TOKEN (DOT, ".") \ + RS_TOKEN (DOT_DOT, "..") \ + RS_TOKEN (DOT_DOT_EQ, "..=") \ + RS_TOKEN (ELLIPSIS, "...") \ + RS_TOKEN (DIV, "/") \ + RS_TOKEN (DIV_EQ, "/=") \ + RS_TOKEN (COLON, ":") \ + RS_TOKEN (SEMICOLON, ";") \ + RS_TOKEN (LEFT_SHIFT, "<<") \ + RS_TOKEN (LEFT_SHIFT_EQ, "<<=") \ + RS_TOKEN (LEFT_ANGLE, "<") \ + RS_TOKEN (LESS_OR_EQUAL, "<=") \ + RS_TOKEN (EQUAL, "=") \ + RS_TOKEN (EQUAL_EQUAL, "==") \ + RS_TOKEN (MATCH_ARROW, "=>") \ + RS_TOKEN (RIGHT_ANGLE, ">") \ + RS_TOKEN (GREATER_OR_EQUAL, ">=") \ + RS_TOKEN (RIGHT_SHIFT, ">>") \ + RS_TOKEN (RIGHT_SHIFT_EQ, ">>=") \ + RS_TOKEN (PATTERN_BIND, "@") \ + RS_TOKEN (TILDE, "~") \ + RS_TOKEN (BACKSLASH, "\\") \ + RS_TOKEN (BACKTICK, "`") \ + RS_TOKEN (CARET, "^") \ + RS_TOKEN (CARET_EQ, "^=") \ + RS_TOKEN (PIPE, "|") \ + RS_TOKEN (PIPE_EQ, "|=") \ + RS_TOKEN (OR, "||") \ + RS_TOKEN (QUESTION_MARK, "?") \ + RS_TOKEN (HASH, "#") \ + /* from here on, dodgy and may not be correct. not operators and may be \ + * symbols */ \ + /* RS_TOKEN(SPACE, " ") probably too dodgy */ \ + /* RS_TOKEN(NEWLINE, "\n")*/ \ + RS_TOKEN (SCOPE_RESOLUTION, "::") /* dodgy */ \ + RS_TOKEN (SINGLE_QUOTE, "'") /* should i differentiate from lifetime? */ \ + RS_TOKEN (DOUBLE_QUOTE, "\"") \ + RS_TOKEN (UNDERSCORE, \ + "_") /* TODO: treat as reserved word like mrustc instead? */ \ + RS_TOKEN (IDENTIFIER, "identifier") \ + RS_TOKEN (INT_LITERAL, \ + "integer literal") /* do different int and float types need \ + different literal types? */ \ + RS_TOKEN (FLOAT_LITERAL, "float literal") \ + RS_TOKEN (STRING_LITERAL, "string literal") \ + RS_TOKEN (CHAR_LITERAL, "character literal") \ + RS_TOKEN (BYTE_STRING_LITERAL, "byte string literal") \ + RS_TOKEN (BYTE_CHAR_LITERAL, "byte character literal") \ + RS_TOKEN (LIFETIME, "lifetime") /* TODO: improve token type */ \ + /* Have "interpolated" tokens (whatever that means)? identifer, path, type, \ + * pattern, */ \ + /* expression, statement, block, meta, item in mrustc (but not directly in \ + * lexer). */ \ + RS_TOKEN (LEFT_PAREN, "(") \ + RS_TOKEN (RIGHT_PAREN, ")") \ + RS_TOKEN (LEFT_CURLY, "{") \ + RS_TOKEN (RIGHT_CURLY, "}") \ + RS_TOKEN (LEFT_SQUARE, "[") \ + RS_TOKEN (RIGHT_SQUARE, "]") \ + /* Macros */ \ + RS_TOKEN (DOLLAR_SIGN, "$") \ + /* Doc Comments */ \ + RS_TOKEN (INNER_DOC_COMMENT, "#![doc]") \ + RS_TOKEN (OUTER_DOC_COMMENT, "#[doc]") \ + /* have "weak" union and 'static keywords? */ \ + \ + RS_TOKEN_KEYWORD (ABSTRACT, "abstract") /* unused */ \ + RS_TOKEN_KEYWORD (AS, "as") \ + RS_TOKEN_KEYWORD (ASYNC, "async") /* unused */ \ + RS_TOKEN_KEYWORD (BECOME, "become") /* unused */ \ + RS_TOKEN_KEYWORD (BOX, "box") /* unused */ \ + RS_TOKEN_KEYWORD (BREAK, "break") \ + RS_TOKEN_KEYWORD (CONST, "const") \ + RS_TOKEN_KEYWORD (CONTINUE, "continue") \ + RS_TOKEN_KEYWORD (CRATE, "crate") \ + /* FIXME: Do we need to add $crate (DOLLAR_CRATE) as a reserved kw? */ \ + RS_TOKEN_KEYWORD (DO, "do") /* unused */ \ + RS_TOKEN_KEYWORD (DYN, "dyn") \ + RS_TOKEN_KEYWORD (ELSE, "else") \ + RS_TOKEN_KEYWORD (ENUM_TOK, "enum") \ + RS_TOKEN_KEYWORD (EXTERN_TOK, "extern") \ + RS_TOKEN_KEYWORD (FALSE_LITERAL, "false") \ + RS_TOKEN_KEYWORD (FINAL_TOK, "final") /* unused */ \ + RS_TOKEN_KEYWORD (FN_TOK, "fn") \ + RS_TOKEN_KEYWORD (FOR, "for") \ + RS_TOKEN_KEYWORD (IF, "if") \ + RS_TOKEN_KEYWORD (IMPL, "impl") \ + RS_TOKEN_KEYWORD (IN, "in") \ + RS_TOKEN_KEYWORD (LET, "let") \ + RS_TOKEN_KEYWORD (LOOP, "loop") \ + RS_TOKEN_KEYWORD (MACRO, "macro") /* unused */ \ + RS_TOKEN_KEYWORD (MATCH_TOK, "match") \ + RS_TOKEN_KEYWORD (MOD, "mod") \ + RS_TOKEN_KEYWORD (MOVE, "move") \ + RS_TOKEN_KEYWORD (MUT, "mut") \ + RS_TOKEN_KEYWORD (OVERRIDE_TOK, "override") /* unused */ \ + RS_TOKEN_KEYWORD (PRIV, "priv") /* unused */ \ + RS_TOKEN_KEYWORD (PUB, "pub") \ + RS_TOKEN_KEYWORD (REF, "ref") \ + RS_TOKEN_KEYWORD (RETURN_TOK, "return") \ + RS_TOKEN_KEYWORD (SELF_ALIAS, \ + "Self") /* mrustc does not treat this as a reserved word*/ \ + RS_TOKEN_KEYWORD (SELF, "self") \ + RS_TOKEN_KEYWORD (STATIC_TOK, "static") \ + RS_TOKEN_KEYWORD (STRUCT_TOK, "struct") \ + RS_TOKEN_KEYWORD (SUPER, "super") \ + RS_TOKEN_KEYWORD (TRAIT, "trait") \ + RS_TOKEN_KEYWORD (TRUE_LITERAL, "true") \ + RS_TOKEN_KEYWORD (TRY, "try") /* unused */ \ + RS_TOKEN_KEYWORD (TYPE, "type") \ + RS_TOKEN_KEYWORD (TYPEOF, "typeof") /* unused */ \ + RS_TOKEN_KEYWORD (UNSAFE, "unsafe") \ + RS_TOKEN_KEYWORD (UNSIZED, "unsized") /* unused */ \ + RS_TOKEN_KEYWORD (USE, "use") \ + RS_TOKEN_KEYWORD (VIRTUAL, "virtual") /* unused */ \ + RS_TOKEN_KEYWORD (WHERE, "where") \ + RS_TOKEN_KEYWORD (WHILE, "while") \ + RS_TOKEN_KEYWORD (YIELD, "yield") /* unused */ \ + \ + RS_TOKEN (LAST_TOKEN, "") + +// Contains all token types. Crappy implementation via x-macros. +enum TokenId +{ +#define RS_TOKEN(name, _) name, +#define RS_TOKEN_KEYWORD(x, y) RS_TOKEN (x, y) + RS_TOKEN_LIST +#undef RS_TOKEN_KEYWORD +#undef RS_TOKEN +}; + +// dodgy "TokenPtr" declaration with Token forward declaration +class Token; +// A smart pointer (shared_ptr) to Token. +typedef std::shared_ptr TokenPtr; +// A smart pointer (shared_ptr) to a constant Token. +typedef std::shared_ptr const_TokenPtr; + +// Hackily defined way to get token description for enum value using x-macros +const char * +get_token_description (TokenId id); +/* Hackily defined way to get token description as a string for enum value using + * x-macros */ +const char * +token_id_to_str (TokenId id); +// Get type hint description as a string. +const char * +get_type_hint_string (PrimitiveCoreType type); + +// Represents a single token. Create using factory static methods. +class Token +{ +private: + // Token kind. + TokenId token_id; + // Token location. + Location locus; + // Associated text (if any) of token. + std::unique_ptr str; + // TODO: maybe remove issues and just store std::string as value? + /* Type hint for token based on lexer data (e.g. type suffix). Does not exist + * for most tokens. */ + PrimitiveCoreType type_hint; + + // Token constructor from token id and location. Has a null string. + Token (TokenId token_id, Location location) + : token_id (token_id), locus (location), str (nullptr), + type_hint (CORETYPE_UNKNOWN) + {} + + // Token constructor from token id, location, and a string. + Token (TokenId token_id, Location location, std::string &¶mStr) + : token_id (token_id), locus (location), + str (new std::string (std::move (paramStr))), type_hint (CORETYPE_UNKNOWN) + {} + + // Token constructor from token id, location, and a char. + Token (TokenId token_id, Location location, char paramChar) + : token_id (token_id), locus (location), + str (new std::string (1, paramChar)), type_hint (CORETYPE_UNKNOWN) + {} + + // Token constructor from token id, location, and a "codepoint". + Token (TokenId token_id, Location location, Codepoint paramCodepoint) + : token_id (token_id), locus (location), + str (new std::string (paramCodepoint.as_string ())), + type_hint (CORETYPE_UNKNOWN) + {} + + // Token constructor from token id, location, a string, and type hint. + Token (TokenId token_id, Location location, std::string &¶mStr, + PrimitiveCoreType parType) + : token_id (token_id), locus (location), + str (new std::string (std::move (paramStr))), type_hint (parType) + {} + +public: + // No default constructor. + Token () = delete; + // Do not copy/assign tokens. + Token (const Token &) = delete; + Token &operator= (const Token &) = delete; + + // Allow moving tokens. + Token (Token &&other) = default; + Token &operator= (Token &&other) = default; + + ~Token () = default; + + /* TODO: make_shared (which saves a heap allocation) does not work with the + * private constructor */ + + // Makes and returns a new TokenPtr (with null string). + static TokenPtr make (TokenId token_id, Location locus) + { + // return std::make_shared (token_id, locus); + return TokenPtr (new Token (token_id, locus)); + } + + // Makes and returns a new TokenPtr of type IDENTIFIER. + static TokenPtr make_identifier (Location locus, std::string &&str) + { + // return std::make_shared (IDENTIFIER, locus, str); + return TokenPtr (new Token (IDENTIFIER, locus, std::move (str))); + } + + // Makes and returns a new TokenPtr of type INT_LITERAL. + static TokenPtr make_int (Location locus, std::string &&str, + PrimitiveCoreType type_hint = CORETYPE_UNKNOWN) + { + // return std::make_shared (INT_LITERAL, locus, str, type_hint); + return TokenPtr ( + new Token (INT_LITERAL, locus, std::move (str), type_hint)); + } + + // Makes and returns a new TokenPtr of type FLOAT_LITERAL. + static TokenPtr make_float (Location locus, std::string &&str, + PrimitiveCoreType type_hint = CORETYPE_UNKNOWN) + { + // return std::make_shared (FLOAT_LITERAL, locus, str, type_hint); + return TokenPtr ( + new Token (FLOAT_LITERAL, locus, std::move (str), type_hint)); + } + + // Makes and returns a new TokenPtr of type STRING_LITERAL. + static TokenPtr make_string (Location locus, std::string &&str) + { + // return std::make_shared (STRING_LITERAL, locus, str, + // CORETYPE_STR); + return TokenPtr ( + new Token (STRING_LITERAL, locus, std::move (str), CORETYPE_STR)); + } + + // Makes and returns a new TokenPtr of type CHAR_LITERAL. + static TokenPtr make_char (Location locus, Codepoint char_lit) + { + // return std::make_shared (CHAR_LITERAL, locus, char_lit); + return TokenPtr (new Token (CHAR_LITERAL, locus, char_lit)); + } + + // Makes and returns a new TokenPtr of type BYTE_CHAR_LITERAL. + static TokenPtr make_byte_char (Location locus, char byte_char) + { + // return std::make_shared (BYTE_CHAR_LITERAL, locus, byte_char); + return TokenPtr (new Token (BYTE_CHAR_LITERAL, locus, byte_char)); + } + + // Makes and returns a new TokenPtr of type BYTE_STRING_LITERAL (fix). + static TokenPtr make_byte_string (Location locus, std::string &&str) + { + // return std::make_shared (BYTE_STRING_LITERAL, locus, str); + return TokenPtr (new Token (BYTE_STRING_LITERAL, locus, std::move (str))); + } + + // Makes and returns a new TokenPtr of type INNER_DOC_COMMENT. + static TokenPtr make_inner_doc_comment (Location locus, std::string &&str) + { + return TokenPtr (new Token (INNER_DOC_COMMENT, locus, std::move (str))); + } + + // Makes and returns a new TokenPtr of type OUTER_DOC_COMMENT. + static TokenPtr make_outer_doc_comment (Location locus, std::string &&str) + { + return TokenPtr (new Token (OUTER_DOC_COMMENT, locus, std::move (str))); + } + + // Makes and returns a new TokenPtr of type LIFETIME. + static TokenPtr make_lifetime (Location locus, std::string &&str) + { + // return std::make_shared (LIFETIME, locus, str); + return TokenPtr (new Token (LIFETIME, locus, std::move (str))); + } + + // Gets id of the token. + TokenId get_id () const { return token_id; } + + // Gets location of the token. + Location get_locus () const { return locus; } + + // Gets string description of the token. + const std::string & + get_str () const; /*{ +// FIXME: put in header again when fix null problem +//gcc_assert(str != nullptr); +if (str == nullptr) { +error_at(get_locus(), "attempted to get string for '%s', which has no string. +returning empty string instead.", get_token_description()); return ""; +} +return *str; +}*/ + + // Gets token's type hint info. + PrimitiveCoreType get_type_hint () const + { + return type_hint == CORETYPE_PURE_DECIMAL ? CORETYPE_UNKNOWN : type_hint; + } + + // diagnostics (error reporting) + const char *get_token_description () const + { + return Rust::get_token_description (token_id); + } + + // debugging + const char *token_id_to_str () const + { + return Rust::token_id_to_str (token_id); + } + + // debugging + const char *get_type_hint_str () const; + + /* Returns whether the token is a literal of any type (int, float, char, + * string, byte char, byte string). */ + bool is_literal () const + { + switch (token_id) + { + case INT_LITERAL: + case FLOAT_LITERAL: + case CHAR_LITERAL: + case STRING_LITERAL: + case BYTE_CHAR_LITERAL: + case BYTE_STRING_LITERAL: + return true; + default: + return false; + } + } + + /* Returns whether the token actually has a string (regardless of whether it + * should or not). */ + bool has_str () const { return str != nullptr; } + + // Returns whether the token should have a string. + bool should_have_str () const + { + return is_literal () || token_id == IDENTIFIER || token_id == LIFETIME; + } + + // Returns whether the token is a pure decimal int literal + bool is_pure_decimal () const { return type_hint == CORETYPE_PURE_DECIMAL; } +}; +} // namespace Rust + +#endif diff --git a/gcc/rust/rust-buffered-queue.h b/gcc/rust/rust-buffered-queue.h new file mode 100644 index 00000000000..afcc4670cac --- /dev/null +++ b/gcc/rust/rust-buffered-queue.h @@ -0,0 +1,204 @@ +// Copyright (C) 2020-2022 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 +// . + +#ifndef RUST_BUFFERED_QUEUE_H +#define RUST_BUFFERED_QUEUE_H + +#include "rust-system.h" + +namespace Rust { +/* Buffered queue implementation. Items are of type T, queue source is of type + * Source. Note that this is owning of the source. */ +template class buffered_queue +{ +public: + // Construct empty queue from Source src. + buffered_queue (Source src) : source (src), start (0), end (0), buffer () {} + + /* disable copying (since source is probably non-copyable) + * TODO is this actually a good idea? If source is non-copyable, it would + * just delete the copy constructor anyway.*/ + buffered_queue (const buffered_queue &other) = delete; + buffered_queue &operator= (const buffered_queue &other) = delete; + + // enable moving + buffered_queue (buffered_queue &&other) = default; + buffered_queue &operator= (buffered_queue &&other) = default; + + // Returns token at position start + n (i.e. n tokens ahead). + T peek (int n) + { + // n should not be behind + rust_assert (n >= 0); + + int num_queued_items = end - start; + int num_items_required = n + 1; + + // if required items go past end of queue, add them to queue + if (num_items_required > num_queued_items) + { + int num_items_to_read = num_items_required - num_queued_items; + + /* if queue length + extra items is larger than buffer size, expand + * buffer */ + if (end + num_items_to_read > (int) buffer.size ()) + { + // Resize the buffer by 1.5x + int new_size = (buffer.size () + num_items_to_read); + new_size += (new_size >> 1); + + // old method: + /* + // create new queue buffer with new size + std::vector new_queue (new_size); + std::copy (buffer.begin () + start, buffer.begin () + end, + new_queue.begin ()); + start = 0; + end = num_queued_items; + // TODO: would move be better here? optimisation for move with + // shared pointer? + + // swap member buffer and new queue buffer + std::swap (buffer, new_queue); + */ + + // TODO: determine overhead of this approach vs copy. Should be + // lower. + std::vector new_queue; + new_queue.reserve (new_size); + new_queue.insert (new_queue.begin (), + std::make_move_iterator (buffer.begin () + start), + std::make_move_iterator (buffer.begin () + end)); + start = 0; + end = num_queued_items; + // fill up rest of vector with junk so that indexing can work + new_queue.insert (new_queue.begin () + end, + new_size - new_queue.size (), T ()); + + buffer = std::move (new_queue); + /* this should be best method - std::move(range) would have + * allocation problems; initial construction would require + * reallocation upon resizing */ + + // validate that buffer is large enough now + rust_assert (end + num_items_to_read <= (int) buffer.size ()); + } + + /* iterate through buffer and invoke operator () on source on values + * past original end */ + for (int i = 0; i < num_items_to_read; i++) + buffer[end + i] = source.next (); + + // move end based on additional items added + end += num_items_to_read; + } + + rust_assert (0 <= start); + rust_assert (start <= end); + rust_assert (end <= (int) buffer.size ()); + + rust_assert (start + n < end); + + // return value at start + n in buffer + return buffer[start + n]; + } + + /* TODO: add faster peek current token to remove overhead of conditional + * branches? */ + + // Advances start by n + 1. + void skip (int n) + { + // Call peek to ensure requested n is actually in queue. + peek (n); + + // Clear queue values from start to n (inclusive). + for (int i = 0; i < (n + 1); i++) + buffer[start + i] = T (); + + // Move start forward by n + 1. + start += (n + 1); + + // Ensure start is not impossible somehow + rust_assert (0 <= start); + rust_assert (start <= end); + + // Compact buffer if empty + if (start == end) + start = end = 0; + } + + /* Inserts element at front of vector. Really dirty hack with terrible + * performance, only use when really needed. */ + void insert_at_front (T elem_to_insert) + { + // TODO: test as this may not work properly + + // Insert actual element in buffer at start. + buffer.insert (buffer.begin (), elem_to_insert); + + /* Increase the end number since added element means all others have shifted + * one along */ + end++; + } + + // Insert at arbitrary position (attempt) + void insert (int index, T elem_to_insert) + { + // TODO: test as this may not work properly + + // n should not be behind + rust_assert (index >= 0); + + // call peek to ensure that the items behind this (at least) are in queue + if (index >= 1) + peek (index - 1); + else + peek (index); + + buffer.insert (buffer.begin () + start + index, std::move (elem_to_insert)); + + end++; + } + + // Replaces the current value in the buffer. Total HACK. + void replace_current_value (T replacement) + { + // call peek to ensure value exists + peek (0); + + buffer[start] = std::move (replacement); + + // don't move start or end + } + +private: + // Source of tokens for queue. + Source source; + + // Begin of range in buffer, inclusive. + int start; + // End of range in buffer, exclusive. + int end; + + // Queue buffer. + std::vector buffer; +}; +} // namespace Rust + +#endif From patchwork Wed Aug 24 11:59:30 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: herron.philip@googlemail.com X-Patchwork-Id: 56984 Return-Path: X-Original-To: patchwork@sourceware.org Delivered-To: patchwork@sourceware.org Received: from server2.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id 2EF8B3955C84 for ; Wed, 24 Aug 2022 12:02:51 +0000 (GMT) X-Original-To: gcc-patches@gcc.gnu.org Delivered-To: gcc-patches@gcc.gnu.org Received: from mail-wr1-x431.google.com (mail-wr1-x431.google.com [IPv6:2a00:1450:4864:20::431]) by sourceware.org (Postfix) with ESMTPS id 2C189385022C; Wed, 24 Aug 2022 12:00:46 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.1 sourceware.org 2C189385022C Authentication-Results: sourceware.org; dmarc=pass (p=quarantine dis=none) header.from=googlemail.com Authentication-Results: sourceware.org; spf=pass smtp.mailfrom=googlemail.com Received: by mail-wr1-x431.google.com with SMTP id n7so20484431wrv.4; Wed, 24 Aug 2022 05:00:46 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=googlemail.com; s=20210112; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc; bh=hus3mtKbo35A1J/fT6U8f2ROeBZZopTU7h4IRTZ33nI=; b=R3S3gvL2VzIxmwn+w0uuwS/WVxEcMiuotpY1OfcC77xWIoixXvBjOfudNDnrd27Cna 8RNvvG+tPVK8XRllZFiLMDWGNiS/g4B2VFB8Nt4qNARge6j8mHWn0PNTC7lqxXk51N4U hGuDS0jNNVIm6XR81td3O/WBU/Vxp/rFZD8ArHKfAWP7PQuN5LO40EoQWAr0h5oerB0m fjWvz299MIyhIhzlWsahG+TCkTcA+ccrc6xdjq/C4hyqzyDvaVyQMF76ztHuY2LyAN1d LeKQ1/Yx7BbyMr0jjwxzmMXWpgFn2CdJP9oN6uLk2lWPAyFmKaqWxmwMgN/SW2oYQTaN UKvA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc; bh=hus3mtKbo35A1J/fT6U8f2ROeBZZopTU7h4IRTZ33nI=; b=2P7Rz6ZdflZvZx0EZPzx3Zw30c2QiYH7n2lxXdIiR+YJwpBFvg91Kh5TdjI0RVo8qE 1r0SQichXEY+YlLfh7XbLRcUutcreHr0PCrcns8T7YhOM9Qy6Z3H8H2P/HVsSSe2q2/D qsBpWkmiG1i0wEQh4tp0hbR/jSduAFFN7f1rN1/1Z6qt2BmqustclEBg7o4U6EL9sZ5Z ac1b8+0AfyI8WJwz3AzUPsDnQdRjeJYO1HWR0VJxolBmCdtl6/NXdxiaBlD5a+/dOCYK /obEQ1wRwd+18J8TfyvEAsMkRE5GXw1HVxgk1NGaDwyMEbc7Cj/Pmf4iXYDe8DmMI6OS mC0A== X-Gm-Message-State: ACgBeo0kwSRwqEv5qqRFU/33DdBYeu0BEY4fcGf/r2uFG+ruIDosWR6x xOpGCd1OVNFNHa8DAzoi21JrlcNlLSs= X-Google-Smtp-Source: AA6agR5YPwm5v4Mx8rrdSOu3jjWmhAhBGUEq9+YIcR+LhES6/KAPifX3SX7BLFG1dT/tvBqoUyTIqw== X-Received: by 2002:a5d:61c7:0:b0:225:307b:b557 with SMTP id q7-20020a5d61c7000000b00225307bb557mr14965248wrv.402.1661342443070; Wed, 24 Aug 2022 05:00:43 -0700 (PDT) Received: from localhost.localdomain ([86.14.124.218]) by smtp.gmail.com with ESMTPSA id cc19-20020a5d5c13000000b0022571d43d32sm1697676wrb.21.2022.08.24.05.00.41 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 24 Aug 2022 05:00:42 -0700 (PDT) From: herron.philip@googlemail.com X-Google-Original-From: philip.herron@embecosm.com To: gcc-patches@gcc.gnu.org Subject: [PATCH Rust front-end v2 11/37] gccrs: Add expansion pass for the Rust front-end Date: Wed, 24 Aug 2022 12:59:30 +0100 Message-Id: <20220824115956.737931-12-philip.herron@embecosm.com> X-Mailer: git-send-email 2.25.1 In-Reply-To: <20220824115956.737931-1-philip.herron@embecosm.com> References: <20220824115956.737931-1-philip.herron@embecosm.com> MIME-Version: 1.0 X-Spam-Status: No, score=-11.4 required=5.0 tests=BAYES_00, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, DKIM_VALID_EF, FREEMAIL_FROM, GIT_PATCH_0, KAM_SHORT, RCVD_IN_DNSWL_NONE, SPF_HELO_NONE, SPF_PASS, TXREP, T_SCC_BODY_TEXT_LINE autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on server2.sourceware.org X-BeenThere: gcc-patches@gcc.gnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: Gcc-patches mailing list List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Reply-To: philip.herron@embecosm.com Cc: Arthur Cohen , The Other , gcc-rust@gcc.gnu.org, Philip Herron Errors-To: gcc-patches-bounces+patchwork=sourceware.org@gcc.gnu.org Sender: "Gcc-patches" From: Arthur Cohen Arthur TODO Co-authored-by: Philip Herron Co-authored-by: The Other --- gcc/rust/expand/rust-attribute-visitor.cc | 3445 ++++++++++++++++++ gcc/rust/expand/rust-attribute-visitor.h | 316 ++ gcc/rust/expand/rust-macro-builtins.cc | 484 +++ gcc/rust/expand/rust-macro-builtins.h | 107 + gcc/rust/expand/rust-macro-expand.cc | 1012 +++++ gcc/rust/expand/rust-macro-expand.h | 366 ++ gcc/rust/expand/rust-macro-invoc-lexer.cc | 29 + gcc/rust/expand/rust-macro-invoc-lexer.h | 64 + gcc/rust/expand/rust-macro-substitute-ctx.cc | 312 ++ gcc/rust/expand/rust-macro-substitute-ctx.h | 93 + 10 files changed, 6228 insertions(+) create mode 100644 gcc/rust/expand/rust-attribute-visitor.cc create mode 100644 gcc/rust/expand/rust-attribute-visitor.h create mode 100644 gcc/rust/expand/rust-macro-builtins.cc create mode 100644 gcc/rust/expand/rust-macro-builtins.h create mode 100644 gcc/rust/expand/rust-macro-expand.cc create mode 100644 gcc/rust/expand/rust-macro-expand.h create mode 100644 gcc/rust/expand/rust-macro-invoc-lexer.cc create mode 100644 gcc/rust/expand/rust-macro-invoc-lexer.h create mode 100644 gcc/rust/expand/rust-macro-substitute-ctx.cc create mode 100644 gcc/rust/expand/rust-macro-substitute-ctx.h diff --git a/gcc/rust/expand/rust-attribute-visitor.cc b/gcc/rust/expand/rust-attribute-visitor.cc new file mode 100644 index 00000000000..8016f9430eb --- /dev/null +++ b/gcc/rust/expand/rust-attribute-visitor.cc @@ -0,0 +1,3445 @@ +// Copyright (C) 2020-2022 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 +// . + +#include "rust-attribute-visitor.h" +#include "rust-session-manager.h" + +namespace Rust { + +// Visitor used to expand attributes. +void +AttrVisitor::expand_struct_fields (std::vector &fields) +{ + for (auto it = fields.begin (); it != fields.end ();) + { + auto &field = *it; + + auto &field_attrs = field.get_outer_attrs (); + expander.expand_cfg_attrs (field_attrs); + if (expander.fails_cfg_with_expand (field_attrs)) + { + it = fields.erase (it); + continue; + } + + expander.push_context (MacroExpander::ContextType::TYPE); + + // expand sub-types of type, but can't strip type itself + auto &type = field.get_field_type (); + type->accept_vis (*this); + + maybe_expand_type (type); + + if (type->is_marked_for_strip ()) + rust_error_at (type->get_locus (), + "cannot strip type in this position"); + + expander.pop_context (); + + // if nothing else happens, increment + ++it; + } +} + +void +AttrVisitor::expand_tuple_fields (std::vector &fields) +{ + for (auto it = fields.begin (); it != fields.end ();) + { + auto &field = *it; + + auto &field_attrs = field.get_outer_attrs (); + expander.expand_cfg_attrs (field_attrs); + if (expander.fails_cfg_with_expand (field_attrs)) + { + it = fields.erase (it); + continue; + } + + // expand sub-types of type, but can't strip type itself + auto &type = field.get_field_type (); + type->accept_vis (*this); + if (type->is_marked_for_strip ()) + rust_error_at (type->get_locus (), + "cannot strip type in this position"); + + // if nothing else happens, increment + ++it; + } +} + +void +AttrVisitor::expand_function_params (std::vector ¶ms) +{ + expander.push_context (MacroExpander::ContextType::TYPE); + + for (auto it = params.begin (); it != params.end ();) + { + auto ¶m = *it; + + auto ¶m_attrs = param.get_outer_attrs (); + expander.expand_cfg_attrs (param_attrs); + if (expander.fails_cfg_with_expand (param_attrs)) + { + it = params.erase (it); + continue; + } + + // TODO: should an unwanted strip lead to break out of loop? + auto &pattern = param.get_pattern (); + pattern->accept_vis (*this); + if (pattern->is_marked_for_strip ()) + rust_error_at (pattern->get_locus (), + "cannot strip pattern in this position"); + + auto &type = param.get_type (); + type->accept_vis (*this); + + maybe_expand_type (type); + + if (type->is_marked_for_strip ()) + rust_error_at (type->get_locus (), + "cannot strip type in this position"); + + // increment + ++it; + } + + expander.pop_context (); +} + +void +AttrVisitor::expand_generic_args (AST::GenericArgs &args) +{ + // lifetime args can't be expanded + // FIXME: Can we have macro invocations for lifetimes? + + expander.push_context (MacroExpander::ContextType::TYPE); + + // expand type args - strip sub-types only + for (auto &arg : args.get_generic_args ()) + { + switch (arg.get_kind ()) + { + case AST::GenericArg::Kind::Type: { + auto &type = arg.get_type (); + type->accept_vis (*this); + maybe_expand_type (type); + + if (type->is_marked_for_strip ()) + rust_error_at (type->get_locus (), + "cannot strip type in this position"); + break; + } + case AST::GenericArg::Kind::Const: { + auto &expr = arg.get_expression (); + expr->accept_vis (*this); + maybe_expand_expr (expr); + + if (expr->is_marked_for_strip ()) + rust_error_at (expr->get_locus (), + "cannot strip expression in this position"); + break; + } + default: + break; + // FIXME: Figure out what to do here if there is ambiguity. Since the + // resolver comes after the expansion, we need to figure out a way to + // strip ambiguous values here + // TODO: Arthur: Probably add a `mark_as_strip` method to `GenericArg` + // or something. This would clean up this whole thing + } + } + + expander.pop_context (); + + // FIXME: Can we have macro invocations in generic type bindings? + // expand binding args - strip sub-types only + for (auto &binding : args.get_binding_args ()) + { + auto &type = binding.get_type (); + type->accept_vis (*this); + + if (type->is_marked_for_strip ()) + rust_error_at (type->get_locus (), + "cannot strip type in this position"); + } +} + +void +AttrVisitor::expand_qualified_path_type (AST::QualifiedPathType &path_type) +{ + expander.push_context (MacroExpander::ContextType::TYPE); + + auto &type = path_type.get_type (); + type->accept_vis (*this); + + maybe_expand_type (type); + + expander.pop_context (); + + if (type->is_marked_for_strip ()) + rust_error_at (type->get_locus (), "cannot strip type in this position"); + + if (path_type.has_as_clause ()) + { + auto &type_path = path_type.get_as_type_path (); + visit (type_path); + if (type_path.is_marked_for_strip ()) + rust_error_at (type_path.get_locus (), + "cannot strip type path in this position"); + } +} + +void +AttrVisitor::AttrVisitor::expand_closure_params ( + std::vector ¶ms) +{ + for (auto it = params.begin (); it != params.end ();) + { + auto ¶m = *it; + + auto ¶m_attrs = param.get_outer_attrs (); + expander.expand_cfg_attrs (param_attrs); + if (expander.fails_cfg_with_expand (param_attrs)) + { + it = params.erase (it); + continue; + } + + auto &pattern = param.get_pattern (); + pattern->accept_vis (*this); + if (pattern->is_marked_for_strip ()) + rust_error_at (pattern->get_locus (), + "cannot strip pattern in this position"); + + if (param.has_type_given ()) + { + expander.push_context (MacroExpander::ContextType::TYPE); + auto &type = param.get_type (); + type->accept_vis (*this); + + maybe_expand_type (type); + + if (type->is_marked_for_strip ()) + rust_error_at (type->get_locus (), + "cannot strip type in this position"); + + expander.pop_context (); + } + + // increment if found nothing else so far + ++it; + } +} + +void +AttrVisitor::expand_self_param (AST::SelfParam &self_param) +{ + if (self_param.has_type ()) + { + expander.push_context (MacroExpander::ContextType::TYPE); + auto &type = self_param.get_type (); + type->accept_vis (*this); + + maybe_expand_type (type); + + if (type->is_marked_for_strip ()) + rust_error_at (type->get_locus (), + "cannot strip type in this position"); + + expander.pop_context (); + } + /* TODO: maybe check for invariants being violated - e.g. both type and + * lifetime? */ +} + +void +AttrVisitor::expand_where_clause (AST::WhereClause &where_clause) +{ + // items cannot be stripped conceptually, so just accept visitor + for (auto &item : where_clause.get_items ()) + item->accept_vis (*this); +} + +void +AttrVisitor::expand_trait_function_decl (AST::TraitFunctionDecl &decl) +{ + // just expand sub-stuff - can't actually strip generic params themselves + for (auto ¶m : decl.get_generic_params ()) + param->accept_vis (*this); + + /* strip function parameters if required - this is specifically + * allowed by spec */ + expand_function_params (decl.get_function_params ()); + + if (decl.has_return_type ()) + { + expander.push_context (MacroExpander::ContextType::TYPE); + + auto &return_type = decl.get_return_type (); + return_type->accept_vis (*this); + + maybe_expand_type (return_type); + + if (return_type->is_marked_for_strip ()) + rust_error_at (return_type->get_locus (), + "cannot strip type in this position"); + + expander.pop_context (); + } + + if (decl.has_where_clause ()) + expand_where_clause (decl.get_where_clause ()); +} + +void +AttrVisitor::expand_trait_method_decl (AST::TraitMethodDecl &decl) +{ + // just expand sub-stuff - can't actually strip generic params themselves + for (auto ¶m : decl.get_generic_params ()) + param->accept_vis (*this); + + /* assuming you can't strip self param - wouldn't be a method + * anymore. spec allows outer attrs on self param, but doesn't + * specify whether cfg is used. */ + expand_self_param (decl.get_self_param ()); + + /* strip function parameters if required - this is specifically + * allowed by spec */ + expand_function_params (decl.get_function_params ()); + + if (decl.has_return_type ()) + { + expander.push_context (MacroExpander::ContextType::TYPE); + + auto &return_type = decl.get_return_type (); + return_type->accept_vis (*this); + + maybe_expand_type (return_type); + + if (return_type->is_marked_for_strip ()) + rust_error_at (return_type->get_locus (), + "cannot strip type in this position"); + + expander.pop_context (); + } + + if (decl.has_where_clause ()) + expand_where_clause (decl.get_where_clause ()); +} + +void +AttrVisitor::visit (AST::Token &) +{ + // shouldn't require? +} +void +AttrVisitor::visit (AST::DelimTokenTree &) +{ + // shouldn't require? +} +void +AttrVisitor::visit (AST::AttrInputMetaItemContainer &) +{ + // shouldn't require? +} +void +AttrVisitor::visit (AST::IdentifierExpr &ident_expr) +{ + // strip test based on outer attrs + expander.expand_cfg_attrs (ident_expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (ident_expr.get_outer_attrs ())) + { + ident_expr.mark_for_strip (); + return; + } +} +void +AttrVisitor::visit (AST::Lifetime &) +{ + // shouldn't require? +} +void +AttrVisitor::visit (AST::LifetimeParam &) +{ + // supposedly does not require - cfg does nothing +} +void +AttrVisitor::visit (AST::ConstGenericParam &) +{ + // likewise +} + +void +AttrVisitor::visit (AST::MacroInvocation ¯o_invoc) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (macro_invoc.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (macro_invoc.get_outer_attrs ())) + { + macro_invoc.mark_for_strip (); + return; + } + + // can't strip simple path + + // I don't think any macro token trees can be stripped in any way + + // TODO: maybe have cfg! macro stripping behaviour here? + expander.expand_invoc (macro_invoc, macro_invoc.has_semicolon ()); +} + +void +AttrVisitor::visit (AST::PathInExpression &path) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (path.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (path.get_outer_attrs ())) + { + path.mark_for_strip (); + return; + } + + for (auto &segment : path.get_segments ()) + { + if (segment.has_generic_args ()) + expand_generic_args (segment.get_generic_args ()); + } +} +void +AttrVisitor::visit (AST::TypePathSegment &) +{ + // shouldn't require +} +void +AttrVisitor::visit (AST::TypePathSegmentGeneric &segment) +{ + // TODO: strip inside generic args + + if (!segment.has_generic_args ()) + return; + + expand_generic_args (segment.get_generic_args ()); +} +void +AttrVisitor::visit (AST::TypePathSegmentFunction &segment) +{ + auto &type_path_function = segment.get_type_path_function (); + + for (auto &type : type_path_function.get_params ()) + { + type->accept_vis (*this); + if (type->is_marked_for_strip ()) + rust_error_at (type->get_locus (), + "cannot strip type in this position"); + } + + if (type_path_function.has_return_type ()) + { + expander.push_context (MacroExpander::ContextType::TYPE); + + auto &return_type = type_path_function.get_return_type (); + return_type->accept_vis (*this); + + maybe_expand_type (return_type); + + if (return_type->is_marked_for_strip ()) + rust_error_at (return_type->get_locus (), + "cannot strip type in this position"); + + expander.pop_context (); + } +} +void +AttrVisitor::visit (AST::TypePath &path) +{ + // this shouldn't strip any segments, but can strip inside them + for (auto &segment : path.get_segments ()) + segment->accept_vis (*this); +} +void +AttrVisitor::visit (AST::QualifiedPathInExpression &path) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (path.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (path.get_outer_attrs ())) + { + path.mark_for_strip (); + return; + } + + expand_qualified_path_type (path.get_qualified_path_type ()); + + for (auto &segment : path.get_segments ()) + { + if (segment.has_generic_args ()) + expand_generic_args (segment.get_generic_args ()); + } +} +void +AttrVisitor::visit (AST::QualifiedPathInType &path) +{ + expand_qualified_path_type (path.get_qualified_path_type ()); + + // this shouldn't strip any segments, but can strip inside them + for (auto &segment : path.get_segments ()) + segment->accept_vis (*this); +} + +void +AttrVisitor::visit (AST::LiteralExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } +} +void +AttrVisitor::visit (AST::AttrInputLiteral &) +{ + // shouldn't require? +} +void +AttrVisitor::visit (AST::MetaItemLitExpr &) +{ + // shouldn't require? +} +void +AttrVisitor::visit (AST::MetaItemPathLit &) +{ + // shouldn't require? +} +void +AttrVisitor::visit (AST::BorrowExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* strip any internal sub-expressions - expression itself isn't + * allowed to have external attributes in this position so can't be + * stripped. */ + auto &borrowed_expr = expr.get_borrowed_expr (); + borrowed_expr->accept_vis (*this); + if (borrowed_expr->is_marked_for_strip ()) + rust_error_at (borrowed_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::DereferenceExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* strip any internal sub-expressions - expression itself isn't + * allowed to have external attributes in this position so can't be + * stripped. */ + auto &dereferenced_expr = expr.get_dereferenced_expr (); + dereferenced_expr->accept_vis (*this); + if (dereferenced_expr->is_marked_for_strip ()) + rust_error_at (dereferenced_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::ErrorPropagationExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* strip any internal sub-expressions - expression itself isn't + * allowed to have external attributes in this position so can't be + * stripped. */ + auto &propagating_expr = expr.get_propagating_expr (); + propagating_expr->accept_vis (*this); + if (propagating_expr->is_marked_for_strip ()) + rust_error_at (propagating_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::NegationExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* strip any internal sub-expressions - expression itself isn't + * allowed to have external attributes in this position so can't be + * stripped. */ + auto &negated_expr = expr.get_negated_expr (); + negated_expr->accept_vis (*this); + if (negated_expr->is_marked_for_strip ()) + rust_error_at (negated_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::ArithmeticOrLogicalExpr &expr) +{ + /* outer attributes never allowed before these. while cannot strip + * two direct descendant expressions, can strip ones below that */ + + /* should have no possibility for outer attrs as would be parsed + * with outer expr */ + auto &l_expr = expr.get_left_expr (); + l_expr->accept_vis (*this); + maybe_expand_expr (l_expr); + + /* should syntactically not have outer attributes, though this may + * not have worked in practice */ + auto &r_expr = expr.get_right_expr (); + r_expr->accept_vis (*this); + maybe_expand_expr (r_expr); + + // ensure that they are not marked for strip + if (expr.get_left_expr ()->is_marked_for_strip ()) + rust_error_at (expr.get_left_expr ()->get_locus (), + "cannot strip expression in this position - outer " + "attributes are never allowed " + "before binary op exprs"); + if (expr.get_right_expr ()->is_marked_for_strip ()) + rust_error_at (expr.get_right_expr ()->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::ComparisonExpr &expr) +{ + /* outer attributes never allowed before these. while cannot strip + * two direct descendant expressions, can strip ones below that */ + + /* should have no possibility for outer attrs as would be parsed + * with outer expr */ + auto &l_expr = expr.get_left_expr (); + l_expr->accept_vis (*this); + maybe_expand_expr (l_expr); + + /* should syntactically not have outer attributes, though this may + * not have worked in practice */ + auto &r_expr = expr.get_right_expr (); + r_expr->accept_vis (*this); + maybe_expand_expr (r_expr); + + // ensure that they are not marked for strip + if (expr.get_left_expr ()->is_marked_for_strip ()) + rust_error_at (expr.get_left_expr ()->get_locus (), + "cannot strip expression in this position - outer " + "attributes are never allowed " + "before binary op exprs"); + if (expr.get_right_expr ()->is_marked_for_strip ()) + rust_error_at (expr.get_right_expr ()->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::LazyBooleanExpr &expr) +{ + /* outer attributes never allowed before these. while cannot strip + * two direct descendant expressions, can strip ones below that */ + + /* should have no possibility for outer attrs as would be parsed + * with outer expr */ + auto &l_expr = expr.get_left_expr (); + l_expr->accept_vis (*this); + maybe_expand_expr (l_expr); + + /* should syntactically not have outer attributes, though this may + * not have worked in practice */ + auto &r_expr = expr.get_right_expr (); + r_expr->accept_vis (*this); + maybe_expand_expr (r_expr); + + // ensure that they are not marked for strip + if (expr.get_left_expr ()->is_marked_for_strip ()) + rust_error_at (expr.get_left_expr ()->get_locus (), + "cannot strip expression in this position - outer " + "attributes are never allowed " + "before binary op exprs"); + if (expr.get_right_expr ()->is_marked_for_strip ()) + rust_error_at (expr.get_right_expr ()->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::TypeCastExpr &expr) +{ + /* outer attributes never allowed before these. while cannot strip + * direct descendant expression, can strip ones below that */ + + auto &casted_expr = expr.get_casted_expr (); + /* should have no possibility for outer attrs as would be parsed + * with outer expr */ + casted_expr->accept_vis (*this); + + // ensure that they are not marked for strip + if (casted_expr->is_marked_for_strip ()) + rust_error_at (casted_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes are never allowed before cast exprs"); + + // TODO: strip sub-types of type + auto &type = expr.get_type_to_cast_to (); + type->accept_vis (*this); + if (type->is_marked_for_strip ()) + rust_error_at (type->get_locus (), "cannot strip type in this position"); +} +void +AttrVisitor::visit (AST::AssignmentExpr &expr) +{ + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* should have no possibility for outer attrs as would be parsed + * with outer expr */ + auto &l_expr = expr.get_left_expr (); + l_expr->accept_vis (*this); + maybe_expand_expr (l_expr); + + /* should syntactically not have outer attributes, though this may + * not have worked in practice */ + auto &r_expr = expr.get_right_expr (); + r_expr->accept_vis (*this); + maybe_expand_expr (r_expr); + + // ensure that they are not marked for strip + if (expr.get_left_expr ()->is_marked_for_strip ()) + rust_error_at (expr.get_left_expr ()->get_locus (), + "cannot strip expression in this position - outer " + "attributes are never allowed " + "before binary op exprs"); + if (expr.get_right_expr ()->is_marked_for_strip ()) + rust_error_at (expr.get_right_expr ()->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::CompoundAssignmentExpr &expr) +{ + /* outer attributes never allowed before these. while cannot strip + * two direct descendant expressions, can strip ones below that */ + + /* should have no possibility for outer attrs as would be parsed + * with outer expr */ + auto &l_expr = expr.get_left_expr (); + l_expr->accept_vis (*this); + maybe_expand_expr (l_expr); + + /* should syntactically not have outer attributes, though this may + * not have worked in practice */ + auto &r_expr = expr.get_right_expr (); + r_expr->accept_vis (*this); + maybe_expand_expr (r_expr); + + // ensure that they are not marked for strip + if (expr.get_left_expr ()->is_marked_for_strip ()) + rust_error_at (expr.get_left_expr ()->get_locus (), + "cannot strip expression in this position - outer " + "attributes are never allowed " + "before binary op exprs"); + if (expr.get_right_expr ()->is_marked_for_strip ()) + rust_error_at (expr.get_right_expr ()->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::GroupedExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* strip test based on inner attrs - spec says these are inner + * attributes, not outer attributes of inner expr */ + expander.expand_cfg_attrs (expr.get_inner_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_inner_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* strip any internal sub-expressions - expression itself isn't + * allowed to have external attributes in this position so can't be + * stripped. */ + auto &inner_expr = expr.get_expr_in_parens (); + inner_expr->accept_vis (*this); + if (inner_expr->is_marked_for_strip ()) + rust_error_at (inner_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::ArrayElemsValues &elems) +{ + /* apparently outer attributes are allowed in "elements of array + * expressions" according to spec */ + expand_pointer_allow_strip (elems.get_values ()); +} +void +AttrVisitor::visit (AST::ArrayElemsCopied &elems) +{ + /* apparently outer attributes are allowed in "elements of array + * expressions" according to spec. on the other hand, it would not + * make conceptual sense to be able to remove either expression. As + * such, not implementing. TODO clear up the ambiguity here */ + + // only intend stripping for internal sub-expressions + auto &copied_expr = elems.get_elem_to_copy (); + copied_expr->accept_vis (*this); + if (copied_expr->is_marked_for_strip ()) + rust_error_at (copied_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); + + auto ©_count = elems.get_num_copies (); + copy_count->accept_vis (*this); + if (copy_count->is_marked_for_strip ()) + rust_error_at (copy_count->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::ArrayExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* strip test based on inner attrs - spec says there are separate + * inner attributes, not just outer attributes of inner exprs */ + expander.expand_cfg_attrs (expr.get_inner_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_inner_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* assuming you can't strip away the ArrayElems type, but can strip + * internal expressions and whatever */ + expr.get_array_elems ()->accept_vis (*this); +} +void +AttrVisitor::visit (AST::ArrayIndexExpr &expr) +{ + /* it is unclear whether outer attributes are supposed to be + * allowed, but conceptually it wouldn't make much sense, but + * having expansion code anyway. TODO */ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* strip any internal sub-expressions - expression itself isn't + * allowed to have external attributes in this position so can't be + * stripped. */ + auto &array_expr = expr.get_array_expr (); + array_expr->accept_vis (*this); + if (array_expr->is_marked_for_strip ()) + rust_error_at (array_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); + + auto &index_expr = expr.get_index_expr (); + index_expr->accept_vis (*this); + if (index_expr->is_marked_for_strip ()) + rust_error_at (index_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::TupleExpr &expr) +{ + /* according to spec, outer attributes are allowed on "elements of + * tuple expressions" */ + + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* strip test based on inner attrs - spec says these are inner + * attributes, not outer attributes of inner expr */ + expander.expand_cfg_attrs (expr.get_inner_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_inner_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* apparently outer attributes are allowed in "elements of tuple + * expressions" according to spec */ + expand_pointer_allow_strip (expr.get_tuple_elems ()); +} +void +AttrVisitor::visit (AST::TupleIndexExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* wouldn't strip this directly (as outer attrs should be + * associated with this level), but any sub-expressions would be + * stripped. Thus, no need to erase when strip check called. */ + auto &tuple_expr = expr.get_tuple_expr (); + tuple_expr->accept_vis (*this); + if (tuple_expr->is_marked_for_strip ()) + rust_error_at (tuple_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::StructExprStruct &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* strip test based on inner attrs - spec says these are inner + * attributes, not outer attributes of inner expr */ + expander.expand_cfg_attrs (expr.get_inner_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_inner_attrs ())) + { + expr.mark_for_strip (); + return; + } + + // strip sub-exprs of path + auto &struct_name = expr.get_struct_name (); + visit (struct_name); + if (struct_name.is_marked_for_strip ()) + rust_error_at (struct_name.get_locus (), + "cannot strip path in this position"); +} +void +AttrVisitor::visit (AST::StructExprFieldIdentifier &) +{ + // as no attrs (at moment, at least), no stripping possible +} +void +AttrVisitor::visit (AST::StructExprFieldIdentifierValue &field) +{ + /* as no attrs possible (at moment, at least), only sub-expression + * stripping is possible */ + auto &value = field.get_value (); + value->accept_vis (*this); + if (value->is_marked_for_strip ()) + rust_error_at (value->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::StructExprFieldIndexValue &field) +{ + /* as no attrs possible (at moment, at least), only sub-expression + * stripping is possible */ + auto &value = field.get_value (); + value->accept_vis (*this); + if (value->is_marked_for_strip ()) + rust_error_at (value->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::StructExprStructFields &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* strip test based on inner attrs - spec says these are inner + * attributes, not outer attributes of inner expr */ + expander.expand_cfg_attrs (expr.get_inner_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_inner_attrs ())) + { + expr.mark_for_strip (); + return; + } + + // strip sub-exprs of path + auto &struct_name = expr.get_struct_name (); + visit (struct_name); + if (struct_name.is_marked_for_strip ()) + rust_error_at (struct_name.get_locus (), + "cannot strip path in this position"); + + /* spec does not specify whether expressions are allowed to be + * stripped at top level of struct fields, but I wouldn't think + * that they would be, so operating under the assumption that only + * sub-expressions can be stripped. */ + for (auto &field : expr.get_fields ()) + { + field->accept_vis (*this); + // shouldn't strip in this + } + + /* struct base presumably can't be stripped, as the '..' is before + * the expression. as such, can only strip sub-expressions. */ + if (expr.has_struct_base ()) + { + auto &base_struct_expr = expr.get_struct_base ().get_base_struct (); + base_struct_expr->accept_vis (*this); + if (base_struct_expr->is_marked_for_strip ()) + rust_error_at (base_struct_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); + } +} +void +AttrVisitor::visit (AST::StructExprStructBase &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* strip test based on inner attrs - spec says these are inner + * attributes, not outer attributes of inner expr */ + expander.expand_cfg_attrs (expr.get_inner_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_inner_attrs ())) + { + expr.mark_for_strip (); + return; + } + + // strip sub-exprs of path + auto &struct_name = expr.get_struct_name (); + visit (struct_name); + if (struct_name.is_marked_for_strip ()) + rust_error_at (struct_name.get_locus (), + "cannot strip path in this position"); + + /* struct base presumably can't be stripped, as the '..' is before + * the expression. as such, can only strip sub-expressions. */ + rust_assert (!expr.get_struct_base ().is_invalid ()); + auto &base_struct_expr = expr.get_struct_base ().get_base_struct (); + base_struct_expr->accept_vis (*this); + if (base_struct_expr->is_marked_for_strip ()) + rust_error_at (base_struct_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::CallExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* should not be outer attrs on "function" expression - outer attrs + * should be associated with call expr as a whole. only sub-expr + * expansion is possible. */ + auto &function = expr.get_function_expr (); + function->accept_vis (*this); + if (function->is_marked_for_strip ()) + rust_error_at (function->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); + + /* spec says outer attributes are specifically allowed for elements + * of call expressions, so full stripping possible */ + // FIXME: Arthur: Figure out how to refactor this - This is similar to + // expanding items in the crate or stmts in blocks + expand_pointer_allow_strip (expr.get_params ()); + auto ¶ms = expr.get_params (); + for (auto it = params.begin (); it != params.end ();) + { + auto &stmt = *it; + + stmt->accept_vis (*this); + + auto final_fragment = expand_macro_fragment_recursive (); + if (final_fragment.should_expand ()) + { + // Remove the current expanded invocation + it = params.erase (it); + for (auto &node : final_fragment.get_nodes ()) + { + it = params.insert (it, node.take_expr ()); + it++; + } + } + else if (stmt->is_marked_for_strip ()) + it = params.erase (it); + else + it++; + } +} +void +AttrVisitor::visit (AST::MethodCallExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* should not be outer attrs on "receiver" expression - outer attrs + * should be associated with call expr as a whole. only sub-expr + * expansion is possible. */ + auto &receiver = expr.get_receiver_expr (); + receiver->accept_vis (*this); + if (receiver->is_marked_for_strip ()) + rust_error_at (receiver->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); + + auto &method_name = expr.get_method_name (); + if (method_name.has_generic_args ()) + expand_generic_args (method_name.get_generic_args ()); + + /* spec says outer attributes are specifically allowed for elements + * of method call expressions, so full stripping possible */ + expand_pointer_allow_strip (expr.get_params ()); +} +void +AttrVisitor::visit (AST::FieldAccessExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* should not be outer attrs on "receiver" expression - outer attrs + * should be associated with field expr as a whole. only sub-expr + * expansion is possible. */ + auto &receiver = expr.get_receiver_expr (); + receiver->accept_vis (*this); + if (receiver->is_marked_for_strip ()) + rust_error_at (receiver->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::ClosureExprInner &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* strip closure parameters if required - this is specifically + * allowed by spec */ + expand_closure_params (expr.get_params ()); + + // can't strip expression itself, but can strip sub-expressions + auto &definition_expr = expr.get_definition_expr (); + definition_expr->accept_vis (*this); + if (definition_expr->is_marked_for_strip ()) + rust_error_at (definition_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} + +void +AttrVisitor::visit (AST::BlockExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* strip test based on inner attrs - spec says there are inner + * attributes, not just outer attributes of inner stmts */ + expander.expand_cfg_attrs (expr.get_inner_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_inner_attrs ())) + { + expr.mark_for_strip (); + return; + } + + std::function (AST::SingleASTNode)> extractor + = [] (AST::SingleASTNode node) { return node.take_stmt (); }; + + expand_macro_children (MacroExpander::BLOCK, expr.get_statements (), + extractor); + + expander.push_context (MacroExpander::BLOCK); + + // strip tail expression if exists - can actually fully remove it + if (expr.has_tail_expr ()) + { + auto &tail_expr = expr.get_tail_expr (); + + tail_expr->accept_vis (*this); + maybe_expand_expr (tail_expr); + + if (tail_expr->is_marked_for_strip ()) + expr.strip_tail_expr (); + } + expander.pop_context (); +} + +void +AttrVisitor::visit (AST::ClosureExprInnerTyped &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* strip closure parameters if required - this is specifically + * allowed by spec */ + expand_closure_params (expr.get_params ()); + + expander.push_context (MacroExpander::ContextType::TYPE); + + // can't strip return type, but can strip sub-types + auto &type = expr.get_return_type (); + type->accept_vis (*this); + + maybe_expand_type (type); + + if (type->is_marked_for_strip ()) + rust_error_at (type->get_locus (), "cannot strip type in this position"); + + expander.pop_context (); + + // can't strip expression itself, but can strip sub-expressions + auto &definition_block = expr.get_definition_block (); + definition_block->accept_vis (*this); + if (definition_block->is_marked_for_strip ()) + rust_error_at (definition_block->get_locus (), + "cannot strip block expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::ContinueExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } +} +void +AttrVisitor::visit (AST::BreakExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* spec does not say that you can have outer attributes on + * expression, so assuming you can't. stripping for sub-expressions + * is the only thing that can be done */ + if (expr.has_break_expr ()) + { + auto &break_expr = expr.get_break_expr (); + + break_expr->accept_vis (*this); + + if (break_expr->is_marked_for_strip ()) + rust_error_at (break_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); + } +} +void +AttrVisitor::visit (AST::RangeFromToExpr &expr) +{ + /* outer attributes never allowed before these. while cannot strip + * two direct descendant expressions, can strip ones below that */ + + /* should have no possibility for outer attrs as would be parsed + * with outer expr */ + expr.get_from_expr ()->accept_vis (*this); + /* should syntactically not have outer attributes, though this may + * not have worked in practice */ + expr.get_to_expr ()->accept_vis (*this); + + // ensure that they are not marked for strip + if (expr.get_from_expr ()->is_marked_for_strip ()) + rust_error_at (expr.get_from_expr ()->get_locus (), + "cannot strip expression in this position - outer " + "attributes are never allowed " + "before range exprs"); + if (expr.get_to_expr ()->is_marked_for_strip ()) + rust_error_at (expr.get_to_expr ()->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::RangeFromExpr &expr) +{ + /* outer attributes never allowed before these. while cannot strip + * direct descendant expression, can strip ones below that */ + + /* should have no possibility for outer attrs as would be parsed + * with outer expr */ + auto &from_expr = expr.get_from_expr (); + + from_expr->accept_vis (*this); + + if (from_expr->is_marked_for_strip ()) + rust_error_at (from_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes are never allowed before range exprs"); +} +void +AttrVisitor::visit (AST::RangeToExpr &expr) +{ + /* outer attributes never allowed before these. while cannot strip + * direct descendant expression, can strip ones below that */ + + /* should syntactically not have outer attributes, though this may + * not have worked in practice */ + auto &to_expr = expr.get_to_expr (); + + to_expr->accept_vis (*this); + + if (to_expr->is_marked_for_strip ()) + rust_error_at (to_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::RangeFullExpr &) +{ + // outer attributes never allowed before these, so no stripping +} +void +AttrVisitor::visit (AST::RangeFromToInclExpr &expr) +{ + /* outer attributes never allowed before these. while cannot strip + * two direct descendant expressions, can strip ones below that */ + + /* should have no possibility for outer attrs as would be parsed + * with outer expr */ + expr.get_from_expr ()->accept_vis (*this); + /* should syntactically not have outer attributes, though this may + * not have worked in practice */ + expr.get_to_expr ()->accept_vis (*this); + + // ensure that they are not marked for strip + if (expr.get_from_expr ()->is_marked_for_strip ()) + rust_error_at (expr.get_from_expr ()->get_locus (), + "cannot strip expression in this position - outer " + "attributes are never allowed " + "before range exprs"); + if (expr.get_to_expr ()->is_marked_for_strip ()) + rust_error_at (expr.get_to_expr ()->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::RangeToInclExpr &expr) +{ + /* outer attributes never allowed before these. while cannot strip + * direct descendant expression, can strip ones below that */ + + /* should syntactically not have outer attributes, though this may + * not have worked in practice */ + auto &to_expr = expr.get_to_expr (); + + to_expr->accept_vis (*this); + + if (to_expr->is_marked_for_strip ()) + rust_error_at (to_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::ReturnExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* spec does not say that you can have outer attributes on + * expression, so assuming you can't. stripping for sub-expressions + * is the only thing that can be done */ + if (expr.has_returned_expr ()) + { + auto &returned_expr = expr.get_returned_expr (); + + returned_expr->accept_vis (*this); + + if (returned_expr->is_marked_for_strip ()) + rust_error_at (returned_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); + } + /* TODO: conceptually, you would maybe be able to remove a returned + * expr - e.g. if you had conditional compilation returning void or + * returning a type. On the other hand, I think that function + * return type cannot be conditionally compiled, so I assumed you + * can't do this either. */ +} +void +AttrVisitor::visit (AST::UnsafeBlockExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + // can't strip block itself, but can strip sub-expressions + auto &block_expr = expr.get_block_expr (); + block_expr->accept_vis (*this); + if (block_expr->is_marked_for_strip ()) + rust_error_at (block_expr->get_locus (), + "cannot strip block expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::LoopExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + // can't strip block itself, but can strip sub-expressions + auto &loop_block = expr.get_loop_block (); + loop_block->accept_vis (*this); + if (loop_block->is_marked_for_strip ()) + rust_error_at (loop_block->get_locus (), + "cannot strip block expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::WhileLoopExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + // can't strip predicate expr itself, but can strip sub-expressions + auto &predicate_expr = expr.get_predicate_expr (); + predicate_expr->accept_vis (*this); + if (predicate_expr->is_marked_for_strip ()) + rust_error_at (predicate_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); + + // can't strip block itself, but can strip sub-expressions + auto &loop_block = expr.get_loop_block (); + loop_block->accept_vis (*this); + if (loop_block->is_marked_for_strip ()) + rust_error_at (loop_block->get_locus (), + "cannot strip block expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::WhileLetLoopExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + for (auto &pattern : expr.get_patterns ()) + { + pattern->accept_vis (*this); + if (pattern->is_marked_for_strip ()) + rust_error_at (pattern->get_locus (), + "cannot strip pattern in this position"); + } + + // can't strip scrutinee expr itself, but can strip sub-expressions + auto &scrutinee_expr = expr.get_scrutinee_expr (); + scrutinee_expr->accept_vis (*this); + if (scrutinee_expr->is_marked_for_strip ()) + rust_error_at (scrutinee_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); + + // can't strip block itself, but can strip sub-expressions + auto &loop_block = expr.get_loop_block (); + loop_block->accept_vis (*this); + if (loop_block->is_marked_for_strip ()) + rust_error_at (loop_block->get_locus (), + "cannot strip block expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::ForLoopExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + // strip sub-patterns of pattern + auto &pattern = expr.get_pattern (); + pattern->accept_vis (*this); + if (pattern->is_marked_for_strip ()) + rust_error_at (pattern->get_locus (), + "cannot strip pattern in this position"); + + // can't strip scrutinee expr itself, but can strip sub-expressions + auto &iterator_expr = expr.get_iterator_expr (); + iterator_expr->accept_vis (*this); + if (iterator_expr->is_marked_for_strip ()) + rust_error_at (iterator_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); + + // can't strip block itself, but can strip sub-expressions + auto &loop_block = expr.get_loop_block (); + loop_block->accept_vis (*this); + if (loop_block->is_marked_for_strip ()) + rust_error_at (loop_block->get_locus (), + "cannot strip block expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::IfExpr &expr) +{ + // rust playground test shows that IfExpr does support outer attrs, at least + // when used as statement + + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + // can't strip condition expr itself, but can strip sub-expressions + auto &condition_expr = expr.get_condition_expr (); + condition_expr->accept_vis (*this); + maybe_expand_expr (condition_expr); + if (condition_expr->is_marked_for_strip ()) + rust_error_at (condition_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); + + // can't strip if block itself, but can strip sub-expressions + auto &if_block = expr.get_if_block (); + if_block->accept_vis (*this); + if (if_block->is_marked_for_strip ()) + rust_error_at (if_block->get_locus (), + "cannot strip block expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::IfExprConseqElse &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + // can't strip condition expr itself, but can strip sub-expressions + auto &condition_expr = expr.get_condition_expr (); + condition_expr->accept_vis (*this); + maybe_expand_expr (condition_expr); + if (condition_expr->is_marked_for_strip ()) + rust_error_at (condition_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); + + // can't strip if block itself, but can strip sub-expressions + auto &if_block = expr.get_if_block (); + if_block->accept_vis (*this); + if (if_block->is_marked_for_strip ()) + rust_error_at (if_block->get_locus (), + "cannot strip block expression in this position - outer " + "attributes not allowed"); + + // can't strip else block itself, but can strip sub-expressions + auto &else_block = expr.get_else_block (); + else_block->accept_vis (*this); + if (else_block->is_marked_for_strip ()) + rust_error_at (else_block->get_locus (), + "cannot strip block expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::IfExprConseqIf &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + // can't strip condition expr itself, but can strip sub-expressions + auto &condition_expr = expr.get_condition_expr (); + condition_expr->accept_vis (*this); + maybe_expand_expr (condition_expr); + if (condition_expr->is_marked_for_strip ()) + rust_error_at (condition_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); + + // can't strip if block itself, but can strip sub-expressions + auto &if_block = expr.get_if_block (); + if_block->accept_vis (*this); + if (if_block->is_marked_for_strip ()) + rust_error_at (if_block->get_locus (), + "cannot strip block expression in this position - outer " + "attributes not allowed"); + + // can't strip if expr itself, but can strip sub-expressions + auto &conseq_if_expr = expr.get_conseq_if_expr (); + conseq_if_expr->accept_vis (*this); + if (conseq_if_expr->is_marked_for_strip ()) + rust_error_at (conseq_if_expr->get_locus (), + "cannot strip consequent if expression in this " + "position - outer attributes not allowed"); +} +void +AttrVisitor::visit (AST::IfExprConseqIfLet &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + // can't strip condition expr itself, but can strip sub-expressions + auto &condition_expr = expr.get_condition_expr (); + condition_expr->accept_vis (*this); + maybe_expand_expr (condition_expr); + if (condition_expr->is_marked_for_strip ()) + rust_error_at (condition_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); + + // can't strip if block itself, but can strip sub-expressions + auto &if_block = expr.get_if_block (); + if_block->accept_vis (*this); + if (if_block->is_marked_for_strip ()) + rust_error_at (if_block->get_locus (), + "cannot strip block expression in this position - outer " + "attributes not allowed"); + + // can't strip if let expr itself, but can strip sub-expressions + auto &conseq_if_let_expr = expr.get_conseq_if_let_expr (); + conseq_if_let_expr->accept_vis (*this); + if (conseq_if_let_expr->is_marked_for_strip ()) + rust_error_at (conseq_if_let_expr->get_locus (), + "cannot strip consequent if let expression in this " + "position - outer attributes not " + "allowed"); +} +void +AttrVisitor::visit (AST::IfLetExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + for (auto &pattern : expr.get_patterns ()) + { + pattern->accept_vis (*this); + if (pattern->is_marked_for_strip ()) + rust_error_at (pattern->get_locus (), + "cannot strip pattern in this position"); + } + + // can't strip value expr itself, but can strip sub-expressions + auto &value_expr = expr.get_value_expr (); + value_expr->accept_vis (*this); + if (value_expr->is_marked_for_strip ()) + rust_error_at (value_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); + + // can't strip if block itself, but can strip sub-expressions + auto &if_block = expr.get_if_block (); + if_block->accept_vis (*this); + if (if_block->is_marked_for_strip ()) + rust_error_at (if_block->get_locus (), + "cannot strip block expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::IfLetExprConseqElse &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + for (auto &pattern : expr.get_patterns ()) + { + pattern->accept_vis (*this); + if (pattern->is_marked_for_strip ()) + rust_error_at (pattern->get_locus (), + "cannot strip pattern in this position"); + } + + // can't strip value expr itself, but can strip sub-expressions + auto &value_expr = expr.get_value_expr (); + value_expr->accept_vis (*this); + if (value_expr->is_marked_for_strip ()) + rust_error_at (value_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); + + // can't strip if block itself, but can strip sub-expressions + auto &if_block = expr.get_if_block (); + if_block->accept_vis (*this); + if (if_block->is_marked_for_strip ()) + rust_error_at (if_block->get_locus (), + "cannot strip block expression in this position - outer " + "attributes not allowed"); + + // can't strip else block itself, but can strip sub-expressions + auto &else_block = expr.get_else_block (); + else_block->accept_vis (*this); + if (else_block->is_marked_for_strip ()) + rust_error_at (else_block->get_locus (), + "cannot strip block expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::IfLetExprConseqIf &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + for (auto &pattern : expr.get_patterns ()) + { + pattern->accept_vis (*this); + if (pattern->is_marked_for_strip ()) + rust_error_at (pattern->get_locus (), + "cannot strip pattern in this position"); + } + + // can't strip value expr itself, but can strip sub-expressions + auto &value_expr = expr.get_value_expr (); + value_expr->accept_vis (*this); + if (value_expr->is_marked_for_strip ()) + rust_error_at (value_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); + + // can't strip if block itself, but can strip sub-expressions + auto &if_block = expr.get_if_block (); + if_block->accept_vis (*this); + if (if_block->is_marked_for_strip ()) + rust_error_at (if_block->get_locus (), + "cannot strip block expression in this position - outer " + "attributes not allowed"); + + // can't strip if expr itself, but can strip sub-expressions + auto &conseq_if_expr = expr.get_conseq_if_expr (); + conseq_if_expr->accept_vis (*this); + if (conseq_if_expr->is_marked_for_strip ()) + rust_error_at (conseq_if_expr->get_locus (), + "cannot strip consequent if expression in this " + "position - outer attributes not allowed"); +} +void +AttrVisitor::visit (AST::IfLetExprConseqIfLet &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + for (auto &pattern : expr.get_patterns ()) + { + pattern->accept_vis (*this); + if (pattern->is_marked_for_strip ()) + rust_error_at (pattern->get_locus (), + "cannot strip pattern in this position"); + } + + // can't strip value expr itself, but can strip sub-expressions + auto &value_expr = expr.get_value_expr (); + value_expr->accept_vis (*this); + if (value_expr->is_marked_for_strip ()) + rust_error_at (value_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); + + // can't strip if block itself, but can strip sub-expressions + auto &if_block = expr.get_if_block (); + if_block->accept_vis (*this); + if (if_block->is_marked_for_strip ()) + rust_error_at (if_block->get_locus (), + "cannot strip block expression in this position - outer " + "attributes not allowed"); + + // can't strip if let expr itself, but can strip sub-expressions + auto &conseq_if_let_expr = expr.get_conseq_if_let_expr (); + conseq_if_let_expr->accept_vis (*this); + if (conseq_if_let_expr->is_marked_for_strip ()) + rust_error_at (conseq_if_let_expr->get_locus (), + "cannot strip consequent if let expression in this " + "position - outer attributes not " + "allowed"); +} +void +AttrVisitor::visit (AST::MatchExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + // inner attr strip test + expander.expand_cfg_attrs (expr.get_inner_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_inner_attrs ())) + { + expr.mark_for_strip (); + return; + } + + // can't strip scrutinee expr itself, but can strip sub-expressions + auto &scrutinee_expr = expr.get_scrutinee_expr (); + scrutinee_expr->accept_vis (*this); + if (scrutinee_expr->is_marked_for_strip ()) + rust_error_at (scrutinee_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); + + // strip match cases + auto &match_cases = expr.get_match_cases (); + for (auto it = match_cases.begin (); it != match_cases.end ();) + { + auto &match_case = *it; + + // strip match case based on outer attributes in match arm + auto &match_arm = match_case.get_arm (); + expander.expand_cfg_attrs (match_arm.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (match_arm.get_outer_attrs ())) + { + // strip match case + it = match_cases.erase (it); + continue; + } + + for (auto &pattern : match_arm.get_patterns ()) + { + pattern->accept_vis (*this); + if (pattern->is_marked_for_strip ()) + rust_error_at (pattern->get_locus (), + "cannot strip pattern in this position"); + } + + /* assuming that guard expression cannot be stripped as + * strictly speaking you would have to strip the whole guard to + * make syntactical sense, which you can't do. as such, only + * strip sub-expressions */ + if (match_arm.has_match_arm_guard ()) + { + auto &guard_expr = match_arm.get_guard_expr (); + guard_expr->accept_vis (*this); + if (guard_expr->is_marked_for_strip ()) + rust_error_at (guard_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); + } + + // strip sub-expressions from match cases + auto &case_expr = match_case.get_expr (); + case_expr->accept_vis (*this); + if (case_expr->is_marked_for_strip ()) + rust_error_at (case_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); + + // increment to next case if haven't continued + ++it; + } +} +void +AttrVisitor::visit (AST::AwaitExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + /* can't strip awaited expr itself, but can strip sub-expressions + * - this is because you can't have no expr to await */ + auto &awaited_expr = expr.get_awaited_expr (); + awaited_expr->accept_vis (*this); + if (awaited_expr->is_marked_for_strip ()) + rust_error_at (awaited_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::AsyncBlockExpr &expr) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (expr.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (expr.get_outer_attrs ())) + { + expr.mark_for_strip (); + return; + } + + // can't strip block itself, but can strip sub-expressions + auto &block_expr = expr.get_block_expr (); + block_expr->accept_vis (*this); + if (block_expr->is_marked_for_strip ()) + rust_error_at (block_expr->get_locus (), + "cannot strip block expression in this position - outer " + "attributes not allowed"); +} + +void +AttrVisitor::visit (AST::TypeParam ¶m) +{ + // outer attributes don't actually do anything, so ignore them + + if (param.has_type_param_bounds ()) + { + // don't strip directly, only components of bounds + for (auto &bound : param.get_type_param_bounds ()) + bound->accept_vis (*this); + } + + if (param.has_type ()) + { + expander.push_context (MacroExpander::ContextType::TYPE); + auto &type = param.get_type (); + type->accept_vis (*this); + + maybe_expand_type (type); + + if (type->is_marked_for_strip ()) + rust_error_at (type->get_locus (), + "cannot strip type in this position"); + + expander.pop_context (); + } +} +void +AttrVisitor::visit (AST::LifetimeWhereClauseItem &) +{ + // shouldn't require +} +void +AttrVisitor::visit (AST::TypeBoundWhereClauseItem &item) +{ + // for lifetimes shouldn't require + + expander.push_context (MacroExpander::ContextType::TYPE); + + auto &type = item.get_type (); + type->accept_vis (*this); + + maybe_expand_type (type); + + if (type->is_marked_for_strip ()) + rust_error_at (type->get_locus (), "cannot strip type in this position"); + + expander.pop_context (); + + // don't strip directly, only components of bounds + for (auto &bound : item.get_type_param_bounds ()) + bound->accept_vis (*this); +} +void +AttrVisitor::visit (AST::Method &method) +{ + // initial test based on outer attrs + expander.expand_cfg_attrs (method.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (method.get_outer_attrs ())) + { + method.mark_for_strip (); + return; + } + + // just expand sub-stuff - can't actually strip generic params themselves + for (auto ¶m : method.get_generic_params ()) + param->accept_vis (*this); + + /* assuming you can't strip self param - wouldn't be a method + * anymore. spec allows outer attrs on self param, but doesn't + * specify whether cfg is used. */ + expand_self_param (method.get_self_param ()); + + /* strip method parameters if required - this is specifically + * allowed by spec */ + expand_function_params (method.get_function_params ()); + + if (method.has_return_type ()) + { + expander.push_context (MacroExpander::ContextType::TYPE); + + auto &return_type = method.get_return_type (); + return_type->accept_vis (*this); + + maybe_expand_type (return_type); + + if (return_type->is_marked_for_strip ()) + rust_error_at (return_type->get_locus (), + "cannot strip type in this position"); + + expander.pop_context (); + } + + if (method.has_where_clause ()) + expand_where_clause (method.get_where_clause ()); + + /* body should always exist - if error state, should have returned + * before now */ + // can't strip block itself, but can strip sub-expressions + auto &block_expr = method.get_definition (); + block_expr->accept_vis (*this); + if (block_expr->is_marked_for_strip ()) + rust_error_at (block_expr->get_locus (), + "cannot strip block expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::Module &module) +{ + // strip test based on outer attrs + expander.expand_cfg_attrs (module.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (module.get_outer_attrs ())) + { + module.mark_for_strip (); + return; + } + + // A loaded module might have inner attributes + if (module.get_kind () == AST::Module::ModuleKind::LOADED) + { + // strip test based on inner attrs + expander.expand_cfg_attrs (module.get_inner_attrs ()); + if (expander.fails_cfg_with_expand (module.get_inner_attrs ())) + { + module.mark_for_strip (); + return; + } + } + + // Parse the module's items if they haven't been expanded and the file + // should be parsed (i.e isn't hidden behind an untrue or impossible cfg + // directive) + if (!module.is_marked_for_strip () + && module.get_kind () == AST::Module::ModuleKind::UNLOADED) + { + module.load_items (); + } + + // strip items if required + expand_pointer_allow_strip (module.get_items ()); +} +void +AttrVisitor::visit (AST::ExternCrate &extern_crate) +{ + // strip test based on outer attrs + expander.expand_cfg_attrs (extern_crate.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (extern_crate.get_outer_attrs ())) + { + extern_crate.mark_for_strip (); + return; + } + + if (!extern_crate.references_self ()) + { + Session &session = Session::get_instance (); + session.load_extern_crate (extern_crate.get_referenced_crate (), + extern_crate.get_locus ()); + } +} +void +AttrVisitor::visit (AST::UseTreeGlob &) +{ + // shouldn't require? +} +void +AttrVisitor::visit (AST::UseTreeList &) +{ + // shouldn't require? +} +void +AttrVisitor::visit (AST::UseTreeRebind &) +{ + // shouldn't require? +} +void +AttrVisitor::visit (AST::UseDeclaration &use_decl) +{ + // strip test based on outer attrs + expander.expand_cfg_attrs (use_decl.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (use_decl.get_outer_attrs ())) + { + use_decl.mark_for_strip (); + return; + } +} +void +AttrVisitor::visit (AST::Function &function) +{ + // initial test based on outer attrs + expander.expand_cfg_attrs (function.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (function.get_outer_attrs ())) + { + function.mark_for_strip (); + return; + } + + // just expand sub-stuff - can't actually strip generic params themselves + for (auto ¶m : function.get_generic_params ()) + param->accept_vis (*this); + + /* strip function parameters if required - this is specifically + * allowed by spec */ + expand_function_params (function.get_function_params ()); + + if (function.has_return_type ()) + { + expander.push_context (MacroExpander::ContextType::TYPE); + + auto &return_type = function.get_return_type (); + return_type->accept_vis (*this); + + maybe_expand_type (return_type); + + if (return_type->is_marked_for_strip ()) + rust_error_at (return_type->get_locus (), + "cannot strip type in this position"); + + expander.pop_context (); + } + + if (function.has_where_clause ()) + expand_where_clause (function.get_where_clause ()); + + /* body should always exist - if error state, should have returned + * before now */ + // can't strip block itself, but can strip sub-expressions + auto &block_expr = function.get_definition (); + block_expr->accept_vis (*this); + if (block_expr->is_marked_for_strip ()) + rust_error_at (block_expr->get_locus (), + "cannot strip block expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::TypeAlias &type_alias) +{ + // initial test based on outer attrs + expander.expand_cfg_attrs (type_alias.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (type_alias.get_outer_attrs ())) + { + type_alias.mark_for_strip (); + return; + } + + // just expand sub-stuff - can't actually strip generic params themselves + for (auto ¶m : type_alias.get_generic_params ()) + param->accept_vis (*this); + + if (type_alias.has_where_clause ()) + expand_where_clause (type_alias.get_where_clause ()); + + auto &type = type_alias.get_type_aliased (); + type->accept_vis (*this); + if (type->is_marked_for_strip ()) + rust_error_at (type->get_locus (), "cannot strip type in this position"); +} +void +AttrVisitor::visit (AST::StructStruct &struct_item) +{ + // initial test based on outer attrs + expander.expand_cfg_attrs (struct_item.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (struct_item.get_outer_attrs ())) + { + struct_item.mark_for_strip (); + return; + } + + // just expand sub-stuff - can't actually strip generic params themselves + for (auto ¶m : struct_item.get_generic_params ()) + param->accept_vis (*this); + + if (struct_item.has_where_clause ()) + expand_where_clause (struct_item.get_where_clause ()); + + /* strip struct fields if required - this is presumably + * allowed by spec */ + expand_struct_fields (struct_item.get_fields ()); +} +void +AttrVisitor::visit (AST::TupleStruct &tuple_struct) +{ + // initial test based on outer attrs + expander.expand_cfg_attrs (tuple_struct.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (tuple_struct.get_outer_attrs ())) + { + tuple_struct.mark_for_strip (); + return; + } + + // just expand sub-stuff - can't actually strip generic params themselves + for (auto ¶m : tuple_struct.get_generic_params ()) + param->accept_vis (*this); + + /* strip struct fields if required - this is presumably + * allowed by spec */ + expand_tuple_fields (tuple_struct.get_fields ()); + + if (tuple_struct.has_where_clause ()) + expand_where_clause (tuple_struct.get_where_clause ()); +} +void +AttrVisitor::visit (AST::EnumItem &item) +{ + // initial test based on outer attrs + expander.expand_cfg_attrs (item.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (item.get_outer_attrs ())) + { + item.mark_for_strip (); + return; + } +} +void +AttrVisitor::visit (AST::EnumItemTuple &item) +{ + // initial test based on outer attrs + expander.expand_cfg_attrs (item.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (item.get_outer_attrs ())) + { + item.mark_for_strip (); + return; + } + + /* strip item fields if required - this is presumably + * allowed by spec */ + expand_tuple_fields (item.get_tuple_fields ()); +} +void +AttrVisitor::visit (AST::EnumItemStruct &item) +{ + // initial test based on outer attrs + expander.expand_cfg_attrs (item.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (item.get_outer_attrs ())) + { + item.mark_for_strip (); + return; + } + + /* strip item fields if required - this is presumably + * allowed by spec */ + expand_struct_fields (item.get_struct_fields ()); +} +void +AttrVisitor::visit (AST::EnumItemDiscriminant &item) +{ + // initial test based on outer attrs + expander.expand_cfg_attrs (item.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (item.get_outer_attrs ())) + { + item.mark_for_strip (); + return; + } + + /* strip any internal sub-expressions - expression itself isn't + * allowed to have external attributes in this position so can't be + * stripped. */ + auto &expr = item.get_expr (); + expr->accept_vis (*this); + if (expr->is_marked_for_strip ()) + rust_error_at (expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::Enum &enum_item) +{ + // initial test based on outer attrs + expander.expand_cfg_attrs (enum_item.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (enum_item.get_outer_attrs ())) + { + enum_item.mark_for_strip (); + return; + } + + // just expand sub-stuff - can't actually strip generic params themselves + for (auto ¶m : enum_item.get_generic_params ()) + param->accept_vis (*this); + + if (enum_item.has_where_clause ()) + expand_where_clause (enum_item.get_where_clause ()); + + /* strip enum fields if required - this is presumably + * allowed by spec */ + expand_pointer_allow_strip (enum_item.get_variants ()); +} +void +AttrVisitor::visit (AST::Union &union_item) +{ + // initial test based on outer attrs + expander.expand_cfg_attrs (union_item.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (union_item.get_outer_attrs ())) + { + union_item.mark_for_strip (); + return; + } + + // just expand sub-stuff - can't actually strip generic params themselves + for (auto ¶m : union_item.get_generic_params ()) + param->accept_vis (*this); + + if (union_item.has_where_clause ()) + expand_where_clause (union_item.get_where_clause ()); + + /* strip union fields if required - this is presumably + * allowed by spec */ + expand_struct_fields (union_item.get_variants ()); +} +void +AttrVisitor::visit (AST::ConstantItem &const_item) +{ + // initial test based on outer attrs + expander.expand_cfg_attrs (const_item.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (const_item.get_outer_attrs ())) + { + const_item.mark_for_strip (); + return; + } + + expander.push_context (MacroExpander::ContextType::TYPE); + + // strip any sub-types + auto &type = const_item.get_type (); + type->accept_vis (*this); + + maybe_expand_type (type); + + if (type->is_marked_for_strip ()) + rust_error_at (type->get_locus (), "cannot strip type in this position"); + + expander.pop_context (); + + /* strip any internal sub-expressions - expression itself isn't + * allowed to have external attributes in this position so can't be + * stripped. */ + auto &expr = const_item.get_expr (); + expr->accept_vis (*this); + if (expr->is_marked_for_strip ()) + rust_error_at (expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::StaticItem &static_item) +{ + // initial test based on outer attrs + expander.expand_cfg_attrs (static_item.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (static_item.get_outer_attrs ())) + { + static_item.mark_for_strip (); + return; + } + + expander.push_context (MacroExpander::ContextType::TYPE); + + // strip any sub-types + auto &type = static_item.get_type (); + type->accept_vis (*this); + + maybe_expand_type (type); + + if (type->is_marked_for_strip ()) + rust_error_at (type->get_locus (), "cannot strip type in this position"); + + expander.pop_context (); + + /* strip any internal sub-expressions - expression itself isn't + * allowed to have external attributes in this position so can't be + * stripped. */ + auto &expr = static_item.get_expr (); + expr->accept_vis (*this); + if (expr->is_marked_for_strip ()) + rust_error_at (expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); +} +void +AttrVisitor::visit (AST::TraitItemFunc &item) +{ + // initial test based on outer attrs + expander.expand_cfg_attrs (item.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (item.get_outer_attrs ())) + { + item.mark_for_strip (); + return; + } + + expand_trait_function_decl (item.get_trait_function_decl ()); + + if (item.has_definition ()) + { + /* strip any internal sub-expressions - expression itself isn't + * allowed to have external attributes in this position so can't be + * stripped. */ + auto &block = item.get_definition (); + block->accept_vis (*this); + if (block->is_marked_for_strip ()) + rust_error_at (block->get_locus (), + "cannot strip block expression in this " + "position - outer attributes not allowed"); + } +} +void +AttrVisitor::visit (AST::TraitItemMethod &item) +{ + // initial test based on outer attrs + expander.expand_cfg_attrs (item.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (item.get_outer_attrs ())) + { + item.mark_for_strip (); + return; + } + + expand_trait_method_decl (item.get_trait_method_decl ()); + + if (item.has_definition ()) + { + /* strip any internal sub-expressions - expression itself isn't + * allowed to have external attributes in this position so can't be + * stripped. */ + auto &block = item.get_definition (); + block->accept_vis (*this); + if (block->is_marked_for_strip ()) + rust_error_at (block->get_locus (), + "cannot strip block expression in this " + "position - outer attributes not allowed"); + } +} +void +AttrVisitor::visit (AST::TraitItemConst &item) +{ + // initial test based on outer attrs + expander.expand_cfg_attrs (item.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (item.get_outer_attrs ())) + { + item.mark_for_strip (); + return; + } + + expander.push_context (MacroExpander::ContextType::TYPE); + + // strip any sub-types + auto &type = item.get_type (); + type->accept_vis (*this); + + maybe_expand_type (type); + + if (type->is_marked_for_strip ()) + rust_error_at (type->get_locus (), "cannot strip type in this position"); + + expander.pop_context (); + + /* strip any internal sub-expressions - expression itself isn't + * allowed to have external attributes in this position so can't be + * stripped */ + if (item.has_expression ()) + { + auto &expr = item.get_expr (); + expr->accept_vis (*this); + if (expr->is_marked_for_strip ()) + rust_error_at (expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); + } +} +void +AttrVisitor::visit (AST::TraitItemType &item) +{ + // initial test based on outer attrs + expander.expand_cfg_attrs (item.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (item.get_outer_attrs ())) + { + item.mark_for_strip (); + return; + } + + if (item.has_type_param_bounds ()) + { + // don't strip directly, only components of bounds + for (auto &bound : item.get_type_param_bounds ()) + bound->accept_vis (*this); + } +} +void +AttrVisitor::visit (AST::Trait &trait) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (trait.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (trait.get_outer_attrs ())) + { + trait.mark_for_strip (); + return; + } + + // strip test based on inner attrs + expander.expand_cfg_attrs (trait.get_inner_attrs ()); + if (expander.fails_cfg_with_expand (trait.get_inner_attrs ())) + { + trait.mark_for_strip (); + return; + } + + // just expand sub-stuff - can't actually strip generic params themselves + for (auto ¶m : trait.get_generic_params ()) + param->accept_vis (*this); + + if (trait.has_type_param_bounds ()) + { + // don't strip directly, only components of bounds + for (auto &bound : trait.get_type_param_bounds ()) + bound->accept_vis (*this); + } + + if (trait.has_where_clause ()) + expand_where_clause (trait.get_where_clause ()); + + std::function (AST::SingleASTNode)> extractor + = [] (AST::SingleASTNode node) { return node.take_trait_item (); }; + + expand_macro_children (MacroExpander::TRAIT, trait.get_trait_items (), + extractor); +} +void +AttrVisitor::visit (AST::InherentImpl &impl) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (impl.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (impl.get_outer_attrs ())) + { + impl.mark_for_strip (); + return; + } + + // strip test based on inner attrs + expander.expand_cfg_attrs (impl.get_inner_attrs ()); + if (expander.fails_cfg_with_expand (impl.get_inner_attrs ())) + { + impl.mark_for_strip (); + return; + } + + // just expand sub-stuff - can't actually strip generic params themselves + for (auto ¶m : impl.get_generic_params ()) + param->accept_vis (*this); + + expander.push_context (MacroExpander::ContextType::TYPE); + + auto &type = impl.get_type (); + type->accept_vis (*this); + + maybe_expand_type (type); + + if (type->is_marked_for_strip ()) + rust_error_at (type->get_locus (), "cannot strip type in this position"); + + expander.pop_context (); + + if (impl.has_where_clause ()) + expand_where_clause (impl.get_where_clause ()); + + std::function (AST::SingleASTNode)> + extractor = [] (AST::SingleASTNode node) { return node.take_impl_item (); }; + + expand_macro_children (MacroExpander::IMPL, impl.get_impl_items (), + extractor); +} +void +AttrVisitor::visit (AST::TraitImpl &impl) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (impl.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (impl.get_outer_attrs ())) + { + impl.mark_for_strip (); + return; + } + + // strip test based on inner attrs + expander.expand_cfg_attrs (impl.get_inner_attrs ()); + if (expander.fails_cfg_with_expand (impl.get_inner_attrs ())) + { + impl.mark_for_strip (); + return; + } + + // just expand sub-stuff - can't actually strip generic params themselves + for (auto ¶m : impl.get_generic_params ()) + param->accept_vis (*this); + + expander.push_context (MacroExpander::ContextType::TYPE); + + auto &type = impl.get_type (); + type->accept_vis (*this); + + maybe_expand_type (type); + + if (type->is_marked_for_strip ()) + rust_error_at (type->get_locus (), "cannot strip type in this position"); + + expander.pop_context (); + + auto &trait_path = impl.get_trait_path (); + visit (trait_path); + if (trait_path.is_marked_for_strip ()) + rust_error_at (trait_path.get_locus (), + "cannot strip typepath in this position"); + + if (impl.has_where_clause ()) + expand_where_clause (impl.get_where_clause ()); + + std::function (AST::SingleASTNode)> + extractor + = [] (AST::SingleASTNode node) { return node.take_trait_impl_item (); }; + + expand_macro_children (MacroExpander::TRAIT_IMPL, impl.get_impl_items (), + extractor); +} +void +AttrVisitor::visit (AST::ExternalStaticItem &item) +{ + // strip test based on outer attrs + expander.expand_cfg_attrs (item.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (item.get_outer_attrs ())) + { + item.mark_for_strip (); + return; + } + + expander.push_context (MacroExpander::ContextType::TYPE); + + auto &type = item.get_type (); + type->accept_vis (*this); + + maybe_expand_type (type); + + if (type->is_marked_for_strip ()) + rust_error_at (type->get_locus (), "cannot strip type in this position"); + + expander.pop_context (); +} +void +AttrVisitor::visit (AST::ExternalFunctionItem &item) +{ + // strip test based on outer attrs + expander.expand_cfg_attrs (item.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (item.get_outer_attrs ())) + { + item.mark_for_strip (); + return; + } + + // just expand sub-stuff - can't actually strip generic params themselves + for (auto ¶m : item.get_generic_params ()) + param->accept_vis (*this); + + /* strip function parameters if required - this is specifically + * allowed by spec */ + auto ¶ms = item.get_function_params (); + for (auto it = params.begin (); it != params.end ();) + { + auto ¶m = *it; + + auto ¶m_attrs = param.get_outer_attrs (); + expander.expand_cfg_attrs (param_attrs); + if (expander.fails_cfg_with_expand (param_attrs)) + { + it = params.erase (it); + continue; + } + + expander.push_context (MacroExpander::ContextType::TYPE); + + auto &type = param.get_type (); + type->accept_vis (*this); + + maybe_expand_type (type); + + if (type->is_marked_for_strip ()) + rust_error_at (type->get_locus (), + "cannot strip type in this position"); + + expander.pop_context (); + + // increment if nothing else happens + ++it; + } + /* NOTE: these are extern function params, which may have different + * rules and restrictions to "normal" function params. So expansion + * handled separately. */ + + /* TODO: assuming that variadic nature cannot be stripped. If this + * is not true, then have code here to do so. */ + + if (item.has_return_type ()) + { + expander.push_context (MacroExpander::ContextType::TYPE); + + auto &return_type = item.get_return_type (); + return_type->accept_vis (*this); + + maybe_expand_type (return_type); + + if (return_type->is_marked_for_strip ()) + rust_error_at (return_type->get_locus (), + "cannot strip type in this position"); + + expander.pop_context (); + } + + if (item.has_where_clause ()) + expand_where_clause (item.get_where_clause ()); +} + +void +AttrVisitor::visit (AST::ExternBlock &block) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (block.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (block.get_outer_attrs ())) + { + block.mark_for_strip (); + return; + } + + // strip test based on inner attrs + expander.expand_cfg_attrs (block.get_inner_attrs ()); + if (expander.fails_cfg_with_expand (block.get_inner_attrs ())) + { + block.mark_for_strip (); + return; + } + + std::function (AST::SingleASTNode)> + extractor + = [] (AST::SingleASTNode node) { return node.take_external_item (); }; + + expand_macro_children (MacroExpander::EXTERN, block.get_extern_items (), + extractor); +} + +// I don't think it would be possible to strip macros without expansion +void +AttrVisitor::visit (AST::MacroMatchFragment &) +{} +void +AttrVisitor::visit (AST::MacroMatchRepetition &) +{} +void +AttrVisitor::visit (AST::MacroMatcher &) +{} +void +AttrVisitor::visit (AST::MacroRulesDefinition &rules_def) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (rules_def.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (rules_def.get_outer_attrs ())) + { + rules_def.mark_for_strip (); + return; + } + + // I don't think any macro rules can be stripped in any way + + auto path = Resolver::CanonicalPath::new_seg (rules_def.get_node_id (), + rules_def.get_rule_name ()); + expander.resolver->get_macro_scope ().insert (path, rules_def.get_node_id (), + rules_def.get_locus ()); + expander.mappings->insert_macro_def (&rules_def); + rust_debug_loc (rules_def.get_locus (), "inserting macro def: [%s]", + path.get ().c_str ()); +} + +void +AttrVisitor::visit (AST::MetaItemPath &) +{} +void +AttrVisitor::visit (AST::MetaItemSeq &) +{} +void +AttrVisitor::visit (AST::MetaWord &) +{} +void +AttrVisitor::visit (AST::MetaNameValueStr &) +{} +void +AttrVisitor::visit (AST::MetaListPaths &) +{} +void +AttrVisitor::visit (AST::MetaListNameValueStr &) +{} + +void +AttrVisitor::visit (AST::LiteralPattern &) +{ + // not possible +} +void +AttrVisitor::visit (AST::IdentifierPattern &pattern) +{ + // can only strip sub-patterns of the inner pattern to bind + if (!pattern.has_pattern_to_bind ()) + return; + + auto &sub_pattern = pattern.get_pattern_to_bind (); + sub_pattern->accept_vis (*this); + if (sub_pattern->is_marked_for_strip ()) + rust_error_at (sub_pattern->get_locus (), + "cannot strip pattern in this position"); +} +void +AttrVisitor::visit (AST::WildcardPattern &) +{ + // not possible +} +void +AttrVisitor::visit (AST::RangePatternBoundLiteral &) +{ + // not possible +} +void +AttrVisitor::visit (AST::RangePatternBoundPath &bound) +{ + // can expand path, but not strip it directly + auto &path = bound.get_path (); + visit (path); + if (path.is_marked_for_strip ()) + rust_error_at (path.get_locus (), "cannot strip path in this position"); +} +void +AttrVisitor::visit (AST::RangePatternBoundQualPath &bound) +{ + // can expand path, but not strip it directly + auto &path = bound.get_qualified_path (); + visit (path); + if (path.is_marked_for_strip ()) + rust_error_at (path.get_locus (), "cannot strip path in this position"); +} +void +AttrVisitor::visit (AST::RangePattern &pattern) +{ + // should have no capability to strip lower or upper bounds, only expand + pattern.get_lower_bound ()->accept_vis (*this); + pattern.get_upper_bound ()->accept_vis (*this); +} +void +AttrVisitor::visit (AST::ReferencePattern &pattern) +{ + auto &sub_pattern = pattern.get_referenced_pattern (); + sub_pattern->accept_vis (*this); + if (sub_pattern->is_marked_for_strip ()) + rust_error_at (sub_pattern->get_locus (), + "cannot strip pattern in this position"); +} +void +AttrVisitor::visit (AST::StructPatternFieldTuplePat &field) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (field.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (field.get_outer_attrs ())) + { + field.mark_for_strip (); + return; + } + + // strip sub-patterns (can't strip top-level pattern) + auto &sub_pattern = field.get_index_pattern (); + sub_pattern->accept_vis (*this); + if (sub_pattern->is_marked_for_strip ()) + rust_error_at (sub_pattern->get_locus (), + "cannot strip pattern in this position"); +} +void +AttrVisitor::visit (AST::StructPatternFieldIdentPat &field) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (field.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (field.get_outer_attrs ())) + { + field.mark_for_strip (); + return; + } + + // strip sub-patterns (can't strip top-level pattern) + auto &sub_pattern = field.get_ident_pattern (); + sub_pattern->accept_vis (*this); + if (sub_pattern->is_marked_for_strip ()) + rust_error_at (sub_pattern->get_locus (), + "cannot strip pattern in this position"); +} +void +AttrVisitor::visit (AST::StructPatternFieldIdent &field) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (field.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (field.get_outer_attrs ())) + { + field.mark_for_strip (); + return; + } +} +void +AttrVisitor::visit (AST::StructPattern &pattern) +{ + // expand (but don't strip) path + auto &path = pattern.get_path (); + visit (path); + if (path.is_marked_for_strip ()) + rust_error_at (path.get_locus (), "cannot strip path in this position"); + + /* TODO: apparently struct pattern fields can have outer attrs. so can they + * be stripped? */ + if (!pattern.has_struct_pattern_elems ()) + return; + + auto &elems = pattern.get_struct_pattern_elems (); + + // assuming you can strip struct pattern fields + expand_pointer_allow_strip (elems.get_struct_pattern_fields ()); + + // assuming you can strip the ".." part + if (elems.has_etc ()) + { + expander.expand_cfg_attrs (elems.get_etc_outer_attrs ()); + if (expander.fails_cfg_with_expand (elems.get_etc_outer_attrs ())) + elems.strip_etc (); + } +} +void +AttrVisitor::visit (AST::TupleStructItemsNoRange &tuple_items) +{ + // can't strip individual patterns, only sub-patterns + for (auto &pattern : tuple_items.get_patterns ()) + { + pattern->accept_vis (*this); + + if (pattern->is_marked_for_strip ()) + rust_error_at (pattern->get_locus (), + "cannot strip pattern in this position"); + // TODO: quit stripping now? or keep going? + } +} +void +AttrVisitor::visit (AST::TupleStructItemsRange &tuple_items) +{ + // can't strip individual patterns, only sub-patterns + for (auto &lower_pattern : tuple_items.get_lower_patterns ()) + { + lower_pattern->accept_vis (*this); + + if (lower_pattern->is_marked_for_strip ()) + rust_error_at (lower_pattern->get_locus (), + "cannot strip pattern in this position"); + // TODO: quit stripping now? or keep going? + } + for (auto &upper_pattern : tuple_items.get_upper_patterns ()) + { + upper_pattern->accept_vis (*this); + + if (upper_pattern->is_marked_for_strip ()) + rust_error_at (upper_pattern->get_locus (), + "cannot strip pattern in this position"); + // TODO: quit stripping now? or keep going? + } +} +void +AttrVisitor::visit (AST::TupleStructPattern &pattern) +{ + // expand (but don't strip) path + auto &path = pattern.get_path (); + visit (path); + if (path.is_marked_for_strip ()) + rust_error_at (path.get_locus (), "cannot strip path in this position"); + + if (pattern.has_items ()) + pattern.get_items ()->accept_vis (*this); +} +void +AttrVisitor::visit (AST::TuplePatternItemsMultiple &tuple_items) +{ + // can't strip individual patterns, only sub-patterns + for (auto &pattern : tuple_items.get_patterns ()) + { + pattern->accept_vis (*this); + + if (pattern->is_marked_for_strip ()) + rust_error_at (pattern->get_locus (), + "cannot strip pattern in this position"); + // TODO: quit stripping now? or keep going? + } +} +void +AttrVisitor::visit (AST::TuplePatternItemsRanged &tuple_items) +{ + // can't strip individual patterns, only sub-patterns + for (auto &lower_pattern : tuple_items.get_lower_patterns ()) + { + lower_pattern->accept_vis (*this); + + if (lower_pattern->is_marked_for_strip ()) + rust_error_at (lower_pattern->get_locus (), + "cannot strip pattern in this position"); + // TODO: quit stripping now? or keep going? + } + for (auto &upper_pattern : tuple_items.get_upper_patterns ()) + { + upper_pattern->accept_vis (*this); + + if (upper_pattern->is_marked_for_strip ()) + rust_error_at (upper_pattern->get_locus (), + "cannot strip pattern in this position"); + // TODO: quit stripping now? or keep going? + } +} +void +AttrVisitor::visit (AST::TuplePattern &pattern) +{ + if (pattern.has_tuple_pattern_items ()) + pattern.get_items ()->accept_vis (*this); +} +void +AttrVisitor::visit (AST::GroupedPattern &pattern) +{ + // can't strip inner pattern, only sub-patterns + auto &pattern_in_parens = pattern.get_pattern_in_parens (); + + pattern_in_parens->accept_vis (*this); + + if (pattern_in_parens->is_marked_for_strip ()) + rust_error_at (pattern_in_parens->get_locus (), + "cannot strip pattern in this position"); +} +void +AttrVisitor::visit (AST::SlicePattern &pattern) +{ + // can't strip individual patterns, only sub-patterns + for (auto &item : pattern.get_items ()) + { + item->accept_vis (*this); + + if (item->is_marked_for_strip ()) + rust_error_at (item->get_locus (), + "cannot strip pattern in this position"); + // TODO: quit stripping now? or keep going? + } +} + +void +AttrVisitor::visit (AST::EmptyStmt &) +{ + // assuming no outer attributes, so nothing can happen +} +void +AttrVisitor::visit (AST::LetStmt &stmt) +{ + // initial strip test based on outer attrs + expander.expand_cfg_attrs (stmt.get_outer_attrs ()); + if (expander.fails_cfg_with_expand (stmt.get_outer_attrs ())) + { + stmt.mark_for_strip (); + return; + } + + // can't strip pattern, but call for sub-patterns + auto &pattern = stmt.get_pattern (); + pattern->accept_vis (*this); + if (pattern->is_marked_for_strip ()) + rust_error_at (pattern->get_locus (), + "cannot strip pattern in this position"); + + // similar for type + if (stmt.has_type ()) + { + expander.push_context (MacroExpander::ContextType::TYPE); + + auto &type = stmt.get_type (); + type->accept_vis (*this); + + maybe_expand_type (type); + + if (type->is_marked_for_strip ()) + rust_error_at (type->get_locus (), + "cannot strip type in this position"); + + expander.pop_context (); + } + + /* strip any internal sub-expressions - expression itself isn't + * allowed to have external attributes in this position so can't be + * stripped */ + if (stmt.has_init_expr ()) + { + auto &init_expr = stmt.get_init_expr (); + init_expr->accept_vis (*this); + + if (init_expr->is_marked_for_strip ()) + rust_error_at (init_expr->get_locus (), + "cannot strip expression in this position - outer " + "attributes not allowed"); + + maybe_expand_expr (init_expr); + } +} +void +AttrVisitor::visit (AST::ExprStmtWithoutBlock &stmt) +{ + // outer attributes associated with expr, so rely on expr + + // guard - should prevent null pointer expr + if (stmt.is_marked_for_strip ()) + return; + + // strip if expr is to be stripped + auto &expr = stmt.get_expr (); + expr->accept_vis (*this); + if (expr->is_marked_for_strip ()) + { + stmt.mark_for_strip (); + return; + } +} +void +AttrVisitor::visit (AST::ExprStmtWithBlock &stmt) +{ + // outer attributes associated with expr, so rely on expr + + // guard - should prevent null pointer expr + if (stmt.is_marked_for_strip ()) + return; + + // strip if expr is to be stripped + auto &expr = stmt.get_expr (); + expr->accept_vis (*this); + if (expr->is_marked_for_strip ()) + { + stmt.mark_for_strip (); + return; + } +} + +void +AttrVisitor::visit (AST::TraitBound &bound) +{ + // nothing in for lifetimes to strip + + // expand but don't strip type path + auto &path = bound.get_type_path (); + visit (path); + if (path.is_marked_for_strip ()) + rust_error_at (path.get_locus (), + "cannot strip type path in this position"); +} +void +AttrVisitor::visit (AST::ImplTraitType &type) +{ + // don't strip directly, only components of bounds + for (auto &bound : type.get_type_param_bounds ()) + bound->accept_vis (*this); +} +void +AttrVisitor::visit (AST::TraitObjectType &type) +{ + // don't strip directly, only components of bounds + for (auto &bound : type.get_type_param_bounds ()) + bound->accept_vis (*this); +} +void +AttrVisitor::visit (AST::ParenthesisedType &type) +{ + // expand but don't strip inner type + auto &inner_type = type.get_type_in_parens (); + inner_type->accept_vis (*this); + if (inner_type->is_marked_for_strip ()) + rust_error_at (inner_type->get_locus (), + "cannot strip type in this position"); +} +void +AttrVisitor::visit (AST::ImplTraitTypeOneBound &type) +{ + // no stripping possible + visit (type.get_trait_bound ()); +} +void +AttrVisitor::visit (AST::TraitObjectTypeOneBound &type) +{ + // no stripping possible + visit (type.get_trait_bound ()); +} +void +AttrVisitor::visit (AST::TupleType &type) +{ + // TODO: assuming that types can't be stripped as types don't have outer + // attributes + for (auto &elem_type : type.get_elems ()) + { + elem_type->accept_vis (*this); + if (elem_type->is_marked_for_strip ()) + rust_error_at (elem_type->get_locus (), + "cannot strip type in this position"); + } +} +void +AttrVisitor::visit (AST::NeverType &) +{ + // no stripping possible +} +void +AttrVisitor::visit (AST::RawPointerType &type) +{ + // expand but don't strip type pointed to + auto &pointed_type = type.get_type_pointed_to (); + pointed_type->accept_vis (*this); + if (pointed_type->is_marked_for_strip ()) + rust_error_at (pointed_type->get_locus (), + "cannot strip type in this position"); +} +void +AttrVisitor::visit (AST::ReferenceType &type) +{ + // expand but don't strip type referenced + auto &referenced_type = type.get_type_referenced (); + referenced_type->accept_vis (*this); + if (referenced_type->is_marked_for_strip ()) + rust_error_at (referenced_type->get_locus (), + "cannot strip type in this position"); +} +void +AttrVisitor::visit (AST::ArrayType &type) +{ + // expand but don't strip type referenced + auto &base_type = type.get_elem_type (); + base_type->accept_vis (*this); + if (base_type->is_marked_for_strip ()) + rust_error_at (base_type->get_locus (), + "cannot strip type in this position"); + + // same for expression + auto &size_expr = type.get_size_expr (); + size_expr->accept_vis (*this); + if (size_expr->is_marked_for_strip ()) + rust_error_at (size_expr->get_locus (), + "cannot strip expression in this position"); +} +void +AttrVisitor::visit (AST::SliceType &type) +{ + // expand but don't strip elem type + auto &elem_type = type.get_elem_type (); + elem_type->accept_vis (*this); + if (elem_type->is_marked_for_strip ()) + rust_error_at (elem_type->get_locus (), + "cannot strip type in this position"); +} +void +AttrVisitor::visit (AST::InferredType &) +{ + // none possible +} +void +AttrVisitor::visit (AST::BareFunctionType &type) +{ + // seem to be no generics + + // presumably function params can be stripped + auto ¶ms = type.get_function_params (); + for (auto it = params.begin (); it != params.end ();) + { + auto ¶m = *it; + + auto ¶m_attrs = param.get_outer_attrs (); + expander.expand_cfg_attrs (param_attrs); + if (expander.fails_cfg_with_expand (param_attrs)) + { + it = params.erase (it); + continue; + } + + expander.push_context (MacroExpander::ContextType::TYPE); + + auto &type = param.get_type (); + type->accept_vis (*this); + + maybe_expand_type (type); + + if (type->is_marked_for_strip ()) + rust_error_at (type->get_locus (), + "cannot strip type in this position"); + + expander.pop_context (); + + // increment if nothing else happens + ++it; + } + + /* TODO: assuming that variadic nature cannot be stripped. If this + * is not true, then have code here to do so. */ + + if (type.has_return_type ()) + { + // FIXME: Can we have type expansion in this position? + // In that case, we need to handle AST::TypeNoBounds on top of just + // AST::Types + auto &return_type = type.get_return_type (); + return_type->accept_vis (*this); + if (return_type->is_marked_for_strip ()) + rust_error_at (return_type->get_locus (), + "cannot strip type in this position"); + } + + // no where clause, apparently +} +void +AttrVisitor::maybe_expand_expr (std::unique_ptr &expr) +{ + auto final_fragment = expand_macro_fragment_recursive (); + if (final_fragment.should_expand ()) + expr = final_fragment.take_expression_fragment (); +} + +void +AttrVisitor::maybe_expand_type (std::unique_ptr &type) +{ + auto final_fragment = expand_macro_fragment_recursive (); + if (final_fragment.should_expand ()) + type = final_fragment.take_type_fragment (); +} +} // namespace Rust diff --git a/gcc/rust/expand/rust-attribute-visitor.h b/gcc/rust/expand/rust-attribute-visitor.h new file mode 100644 index 00000000000..0f9d1065334 --- /dev/null +++ b/gcc/rust/expand/rust-attribute-visitor.h @@ -0,0 +1,316 @@ +// Copyright (C) 2020-2022 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 +// . + +#include "rust-ast-visitor.h" +#include "rust-ast.h" +#include "rust-macro-expand.h" + +namespace Rust { +// Visitor used to expand attributes. +class AttrVisitor : public AST::ASTVisitor +{ +private: + MacroExpander &expander; + void maybe_expand_expr (std::unique_ptr &expr); + void maybe_expand_type (std::unique_ptr &expr); + +public: + AttrVisitor (MacroExpander &expander) : expander (expander) {} + + void expand_struct_fields (std::vector &fields); + void expand_tuple_fields (std::vector &fields); + void expand_function_params (std::vector ¶ms); + void expand_generic_args (AST::GenericArgs &args); + void expand_qualified_path_type (AST::QualifiedPathType &path_type); + void expand_closure_params (std::vector ¶ms); + void expand_self_param (AST::SelfParam &self_param); + void expand_where_clause (AST::WhereClause &where_clause); + void expand_trait_function_decl (AST::TraitFunctionDecl &decl); + void expand_trait_method_decl (AST::TraitMethodDecl &decl); + + /** + * Expand The current macro fragment recursively until it could not be + * expanded further. + * + * The return value checking works because correctly + * expanded fragment can never be an error (if the fragment can not be + * expanded, a stand-in error fragment will be returned; for fragments that + * could not be further expanded: the fragment prior to the expansion failure + * will be returned). + * + * @return Either the expanded fragment or an empty errored-out fragment + * indicating an expansion failure. + */ + AST::ASTFragment expand_macro_fragment_recursive () + { + auto fragment = expander.take_expanded_fragment (*this); + unsigned int original_depth = expander.expansion_depth; + auto final_fragment = AST::ASTFragment ({}, true); + + while (fragment.should_expand ()) + { + final_fragment = std::move (fragment); + expander.expansion_depth++; + // further expand the previously expanded macro fragment + auto new_fragment = expander.take_expanded_fragment (*this); + if (new_fragment.is_error ()) + break; + fragment = std::move (new_fragment); + } + expander.expansion_depth = original_depth; + return final_fragment; + } + + /** + * Expand a set of values, erasing them if they are marked for strip, and + * replacing them with expanded macro nodes if necessary. + * This function is slightly different from `expand_pointer_allow_strip` as + * it can only be called in certain expansion contexts - where macro + * invocations are allowed. + * + * @param ctx Context to use for macro expansion + * @param values Iterable reference over values to replace or erase + * @param extractor Function to call when replacing values with the content + * of an expanded AST node + */ + template + void expand_macro_children (MacroExpander::ContextType ctx, T &values, + std::function extractor) + { + expander.push_context (ctx); + + for (auto it = values.begin (); it != values.end ();) + { + auto &value = *it; + + // mark for stripping if required + value->accept_vis (*this); + + // recursively expand the children + auto final_fragment = expand_macro_fragment_recursive (); + + if (final_fragment.should_expand ()) + { + it = values.erase (it); + for (auto &node : final_fragment.get_nodes ()) + { + auto new_node = extractor (node); + if (new_node != nullptr && !new_node->is_marked_for_strip ()) + { + it = values.insert (it, std::move (new_node)); + it++; + } + } + } + else if (value->is_marked_for_strip ()) + { + it = values.erase (it); + } + else + { + ++it; + } + } + + expander.pop_context (); + } + + template void expand_pointer_allow_strip (T &values) + { + for (auto it = values.begin (); it != values.end ();) + { + auto &value = *it; + + // mark for stripping if required + value->accept_vis (*this); + if (value->is_marked_for_strip ()) + { + it = values.erase (it); + } + else + { + ++it; + } + } + } + + void visit (AST::Token &) override; + void visit (AST::DelimTokenTree &) override; + void visit (AST::AttrInputMetaItemContainer &) override; + void visit (AST::IdentifierExpr &ident_expr) override; + void visit (AST::Lifetime &) override; + void visit (AST::LifetimeParam &) override; + void visit (AST::ConstGenericParam &) override; + + void visit (AST::MacroInvocation ¯o_invoc) override; + + void visit (AST::PathInExpression &path) override; + void visit (AST::TypePathSegment &) override; + void visit (AST::TypePathSegmentGeneric &segment) override; + void visit (AST::TypePathSegmentFunction &segment) override; + void visit (AST::TypePath &path) override; + void visit (AST::QualifiedPathInExpression &path) override; + void visit (AST::QualifiedPathInType &path) override; + + void visit (AST::LiteralExpr &expr) override; + void visit (AST::AttrInputLiteral &) override; + void visit (AST::MetaItemLitExpr &) override; + void visit (AST::MetaItemPathLit &) override; + void visit (AST::BorrowExpr &expr) override; + void visit (AST::DereferenceExpr &expr) override; + void visit (AST::ErrorPropagationExpr &expr) override; + void visit (AST::NegationExpr &expr) override; + void visit (AST::ArithmeticOrLogicalExpr &expr) override; + void visit (AST::ComparisonExpr &expr) override; + void visit (AST::LazyBooleanExpr &expr) override; + void visit (AST::TypeCastExpr &expr) override; + void visit (AST::AssignmentExpr &expr) override; + void visit (AST::CompoundAssignmentExpr &expr) override; + void visit (AST::GroupedExpr &expr) override; + void visit (AST::ArrayElemsValues &elems) override; + void visit (AST::ArrayElemsCopied &elems) override; + void visit (AST::ArrayExpr &expr) override; + void visit (AST::ArrayIndexExpr &expr) override; + void visit (AST::TupleExpr &expr) override; + void visit (AST::TupleIndexExpr &expr) override; + void visit (AST::StructExprStruct &expr) override; + void visit (AST::StructExprFieldIdentifier &) override; + void visit (AST::StructExprFieldIdentifierValue &field) override; + + void visit (AST::StructExprFieldIndexValue &field) override; + void visit (AST::StructExprStructFields &expr) override; + void visit (AST::StructExprStructBase &expr) override; + void visit (AST::CallExpr &expr) override; + void visit (AST::MethodCallExpr &expr) override; + void visit (AST::FieldAccessExpr &expr) override; + void visit (AST::ClosureExprInner &expr) override; + + void visit (AST::BlockExpr &expr) override; + + void visit (AST::ClosureExprInnerTyped &expr) override; + void visit (AST::ContinueExpr &expr) override; + void visit (AST::BreakExpr &expr) override; + void visit (AST::RangeFromToExpr &expr) override; + void visit (AST::RangeFromExpr &expr) override; + void visit (AST::RangeToExpr &expr) override; + void visit (AST::RangeFullExpr &) override; + void visit (AST::RangeFromToInclExpr &expr) override; + void visit (AST::RangeToInclExpr &expr) override; + void visit (AST::ReturnExpr &expr) override; + void visit (AST::UnsafeBlockExpr &expr) override; + void visit (AST::LoopExpr &expr) override; + void visit (AST::WhileLoopExpr &expr) override; + void visit (AST::WhileLetLoopExpr &expr) override; + void visit (AST::ForLoopExpr &expr) override; + void visit (AST::IfExpr &expr) override; + void visit (AST::IfExprConseqElse &expr) override; + void visit (AST::IfExprConseqIf &expr) override; + void visit (AST::IfExprConseqIfLet &expr) override; + void visit (AST::IfLetExpr &expr) override; + void visit (AST::IfLetExprConseqElse &expr) override; + void visit (AST::IfLetExprConseqIf &expr) override; + void visit (AST::IfLetExprConseqIfLet &expr) override; + void visit (AST::MatchExpr &expr) override; + void visit (AST::AwaitExpr &expr) override; + void visit (AST::AsyncBlockExpr &expr) override; + void visit (AST::TypeParam ¶m) override; + void visit (AST::LifetimeWhereClauseItem &) override; + void visit (AST::TypeBoundWhereClauseItem &item) override; + void visit (AST::Method &method) override; + void visit (AST::Module &module) override; + void visit (AST::ExternCrate &crate) override; + void visit (AST::UseTreeGlob &) override; + void visit (AST::UseTreeList &) override; + void visit (AST::UseTreeRebind &) override; + void visit (AST::UseDeclaration &use_decl) override; + void visit (AST::Function &function) override; + void visit (AST::TypeAlias &type_alias) override; + void visit (AST::StructStruct &struct_item) override; + void visit (AST::TupleStruct &tuple_struct) 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; + void visit (AST::Enum &enum_item) override; + void visit (AST::Union &union_item) override; + void visit (AST::ConstantItem &const_item) override; + void visit (AST::StaticItem &static_item) override; + void visit (AST::TraitItemFunc &item) override; + void visit (AST::TraitItemMethod &item) override; + void visit (AST::TraitItemConst &item) override; + void visit (AST::TraitItemType &item) override; + void visit (AST::Trait &trait) override; + void visit (AST::InherentImpl &impl) override; + void visit (AST::TraitImpl &impl) override; + void visit (AST::ExternalStaticItem &item) override; + void visit (AST::ExternalFunctionItem &item) override; + void visit (AST::ExternBlock &block) override; + + // I don't think it would be possible to strip macros without expansion + void visit (AST::MacroMatchFragment &) override; + void visit (AST::MacroMatchRepetition &) override; + void visit (AST::MacroMatcher &) override; + void visit (AST::MacroRulesDefinition &rules_def) override; + void visit (AST::MetaItemPath &) override; + void visit (AST::MetaItemSeq &) override; + void visit (AST::MetaWord &) override; + void visit (AST::MetaNameValueStr &) override; + void visit (AST::MetaListPaths &) override; + void visit (AST::MetaListNameValueStr &) override; + void visit (AST::LiteralPattern &) override; + void visit (AST::IdentifierPattern &pattern) override; + void visit (AST::WildcardPattern &) override; + void visit (AST::RangePatternBoundLiteral &) override; + void visit (AST::RangePatternBoundPath &bound) override; + void visit (AST::RangePatternBoundQualPath &bound) override; + void visit (AST::RangePattern &pattern) override; + void visit (AST::ReferencePattern &pattern) override; + void visit (AST::StructPatternFieldTuplePat &field) override; + void visit (AST::StructPatternFieldIdentPat &field) override; + void visit (AST::StructPatternFieldIdent &field) override; + void visit (AST::StructPattern &pattern) override; + void visit (AST::TupleStructItemsNoRange &tuple_items) override; + void visit (AST::TupleStructItemsRange &tuple_items) override; + void visit (AST::TupleStructPattern &pattern) override; + void visit (AST::TuplePatternItemsMultiple &tuple_items) override; + void visit (AST::TuplePatternItemsRanged &tuple_items) override; + void visit (AST::TuplePattern &pattern) override; + void visit (AST::GroupedPattern &pattern) override; + void visit (AST::SlicePattern &pattern) override; + + void visit (AST::EmptyStmt &) override; + void visit (AST::LetStmt &stmt) override; + void visit (AST::ExprStmtWithoutBlock &stmt) override; + void visit (AST::ExprStmtWithBlock &stmt) override; + + void visit (AST::TraitBound &bound) override; + void visit (AST::ImplTraitType &type) override; + void visit (AST::TraitObjectType &type) override; + void visit (AST::ParenthesisedType &type) override; + void visit (AST::ImplTraitTypeOneBound &type) override; + void visit (AST::TraitObjectTypeOneBound &type) override; + void visit (AST::TupleType &type) override; + void visit (AST::NeverType &) override; + void visit (AST::RawPointerType &type) override; + void visit (AST::ReferenceType &type) override; + void visit (AST::ArrayType &type) override; + void visit (AST::SliceType &type) override; + void visit (AST::InferredType &) override; + void visit (AST::BareFunctionType &type) override; +}; +} // namespace Rust diff --git a/gcc/rust/expand/rust-macro-builtins.cc b/gcc/rust/expand/rust-macro-builtins.cc new file mode 100644 index 00000000000..5eace13d197 --- /dev/null +++ b/gcc/rust/expand/rust-macro-builtins.cc @@ -0,0 +1,484 @@ +// Copyright (C) 2020-2022 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 +// . + +#include "rust-macro-builtins.h" +#include "rust-diagnostics.h" +#include "rust-expr.h" +#include "rust-session-manager.h" +#include "rust-macro-invoc-lexer.h" +#include "rust-lex.h" +#include "rust-parse.h" + +namespace Rust { +namespace { +std::unique_ptr +make_string (Location locus, std::string value) +{ + return std::unique_ptr ( + new AST::LiteralExpr (value, AST::Literal::STRING, + PrimitiveCoreType::CORETYPE_STR, {}, locus)); +} + +/* Match the end token of a macro given the start delimiter of the macro */ + +static inline TokenId +macro_end_token (AST::DelimTokenTree &invoc_token_tree, + Parser &parser) +{ + auto last_token_id = TokenId::RIGHT_CURLY; + switch (invoc_token_tree.get_delim_type ()) + { + case AST::DelimType::PARENS: + last_token_id = TokenId::RIGHT_PAREN; + rust_assert (parser.skip_token (LEFT_PAREN)); + break; + + case AST::DelimType::CURLY: + rust_assert (parser.skip_token (LEFT_CURLY)); + break; + + case AST::DelimType::SQUARE: + last_token_id = TokenId::RIGHT_SQUARE; + rust_assert (parser.skip_token (LEFT_SQUARE)); + break; + } + + return last_token_id; +} + +/* Parse a single string literal from the given delimited token tree, + and return the LiteralExpr for it. Allow for an optional trailing comma, + but otherwise enforce that these are the only tokens. */ + +std::unique_ptr +parse_single_string_literal (AST::DelimTokenTree &invoc_token_tree, + Location invoc_locus) +{ + MacroInvocLexer lex (invoc_token_tree.to_token_stream ()); + Parser parser (lex); + + auto last_token_id = macro_end_token (invoc_token_tree, parser); + + std::unique_ptr lit_expr = nullptr; + + if (parser.peek_current_token ()->get_id () == STRING_LITERAL) + { + lit_expr = parser.parse_literal_expr (); + parser.maybe_skip_token (COMMA); + if (parser.peek_current_token ()->get_id () != last_token_id) + { + lit_expr = nullptr; + rust_error_at (invoc_locus, "macro takes 1 argument"); + } + } + else if (parser.peek_current_token ()->get_id () == last_token_id) + rust_error_at (invoc_locus, "macro takes 1 argument"); + else + rust_error_at (invoc_locus, "argument must be a string literal"); + + parser.skip_token (last_token_id); + + return lit_expr; +} + +/* Treat PATH as a path relative to the source file currently being + compiled, and return the absolute path for it. */ + +std::string +source_relative_path (std::string path, Location locus) +{ + std::string compile_fname + = Session::get_instance ().linemap->location_file (locus); + + auto dir_separator_pos = compile_fname.rfind (file_separator); + + /* If there is no file_separator in the path, use current dir ('.'). */ + std::string dirname; + if (dir_separator_pos == std::string::npos) + dirname = std::string (".") + file_separator; + else + dirname = compile_fname.substr (0, dir_separator_pos) + file_separator; + + return dirname + path; +} + +/* Read the full contents of the file FILENAME and return them in a vector. + FIXME: platform specific. */ + +std::vector +load_file_bytes (const char *filename) +{ + RAIIFile file_wrap (filename); + if (file_wrap.get_raw () == nullptr) + { + rust_error_at (Location (), "cannot open filename %s: %m", filename); + return std::vector (); + } + + FILE *f = file_wrap.get_raw (); + fseek (f, 0L, SEEK_END); + long fsize = ftell (f); + fseek (f, 0L, SEEK_SET); + + std::vector buf (fsize); + + if (fread (&buf[0], fsize, 1, f) != 1) + { + rust_error_at (Location (), "error reading file %s: %m", filename); + return std::vector (); + } + + return buf; +} +} // namespace + +AST::ASTFragment +MacroBuiltin::assert (Location invoc_locus, AST::MacroInvocData &invoc) +{ + rust_debug ("assert!() called"); + + return AST::ASTFragment::create_error (); +} + +AST::ASTFragment +MacroBuiltin::file (Location invoc_locus, AST::MacroInvocData &invoc) +{ + auto current_file + = Session::get_instance ().linemap->location_file (invoc_locus); + auto file_str = AST::SingleASTNode (make_string (invoc_locus, current_file)); + + return AST::ASTFragment ({file_str}); +} + +AST::ASTFragment +MacroBuiltin::column (Location invoc_locus, AST::MacroInvocData &invoc) +{ + auto current_column + = Session::get_instance ().linemap->location_to_column (invoc_locus); + + auto column_no = AST::SingleASTNode (std::unique_ptr ( + new AST::LiteralExpr (std::to_string (current_column), AST::Literal::INT, + PrimitiveCoreType::CORETYPE_U32, {}, invoc_locus))); + + return AST::ASTFragment ({column_no}); +} + +/* Expand builtin macro include_bytes!("filename"), which includes the contents + of the given file as reference to a byte array. Yields an expression of type + &'static [u8; N]. */ + +AST::ASTFragment +MacroBuiltin::include_bytes (Location invoc_locus, AST::MacroInvocData &invoc) +{ + /* Get target filename from the macro invocation, which is treated as a path + relative to the include!-ing file (currently being compiled). */ + auto lit_expr + = parse_single_string_literal (invoc.get_delim_tok_tree (), invoc_locus); + if (lit_expr == nullptr) + return AST::ASTFragment::create_error (); + + std::string target_filename + = source_relative_path (lit_expr->as_string (), invoc_locus); + + std::vector bytes = load_file_bytes (target_filename.c_str ()); + + /* Is there a more efficient way to do this? */ + std::vector> elts; + for (uint8_t b : bytes) + { + elts.emplace_back ( + new AST::LiteralExpr (std::string (1, (char) b), AST::Literal::BYTE, + PrimitiveCoreType::CORETYPE_U8, + {} /* outer_attrs */, invoc_locus)); + } + + auto elems = std::unique_ptr ( + new AST::ArrayElemsValues (std::move (elts), invoc_locus)); + + auto array = std::unique_ptr ( + new AST::ArrayExpr (std::move (elems), {}, {}, invoc_locus)); + + auto borrow = std::unique_ptr ( + new AST::BorrowExpr (std::move (array), false, false, {}, invoc_locus)); + + auto node = AST::SingleASTNode (std::move (borrow)); + return AST::ASTFragment ({node}); +} + +/* Expand builtin macro include_str!("filename"), which includes the contents + of the given file as a string. The file must be UTF-8 encoded. Yields an + expression of type &'static str. */ + +AST::ASTFragment +MacroBuiltin::include_str (Location invoc_locus, AST::MacroInvocData &invoc) +{ + /* Get target filename from the macro invocation, which is treated as a path + relative to the include!-ing file (currently being compiled). */ + auto lit_expr + = parse_single_string_literal (invoc.get_delim_tok_tree (), invoc_locus); + if (lit_expr == nullptr) + return AST::ASTFragment::create_error (); + + std::string target_filename + = source_relative_path (lit_expr->as_string (), invoc_locus); + + std::vector bytes = load_file_bytes (target_filename.c_str ()); + + /* FIXME: Enforce that the file contents are valid UTF-8. */ + std::string str ((const char *) &bytes[0], bytes.size ()); + + auto node = AST::SingleASTNode (make_string (invoc_locus, str)); + return AST::ASTFragment ({node}); +} + +/* Expand builtin macro compile_error!("error"), which forces a compile error + during the compile time. */ +AST::ASTFragment +MacroBuiltin::compile_error (Location invoc_locus, AST::MacroInvocData &invoc) +{ + auto lit_expr + = parse_single_string_literal (invoc.get_delim_tok_tree (), invoc_locus); + if (lit_expr == nullptr) + return AST::ASTFragment::create_error (); + + std::string error_string = lit_expr->as_string (); + rust_error_at (invoc_locus, "%s", error_string.c_str ()); + + return AST::ASTFragment::create_error (); +} + +/* Expand builtin macro concat!(), which joins all the literal parameters + into a string with no delimiter. */ + +AST::ASTFragment +MacroBuiltin::concat (Location invoc_locus, AST::MacroInvocData &invoc) +{ + auto invoc_token_tree = invoc.get_delim_tok_tree (); + MacroInvocLexer lex (invoc_token_tree.to_token_stream ()); + Parser parser (lex); + + auto str = std::string (); + bool has_error = false; + + auto last_token_id = macro_end_token (invoc_token_tree, parser); + + /* NOTE: concat! could accept no argument, so we don't have any checks here */ + while (parser.peek_current_token ()->get_id () != last_token_id) + { + auto lit_expr = parser.parse_literal_expr (); + if (lit_expr) + { + str += lit_expr->as_string (); + } + else + { + auto current_token = parser.peek_current_token (); + rust_error_at (current_token->get_locus (), + "argument must be a constant literal"); + has_error = true; + // Just crash if the current token can't be skipped + rust_assert (parser.skip_token (current_token->get_id ())); + } + parser.maybe_skip_token (COMMA); + } + + parser.skip_token (last_token_id); + + if (has_error) + return AST::ASTFragment::create_error (); + + auto node = AST::SingleASTNode (make_string (invoc_locus, str)); + return AST::ASTFragment ({node}); +} + +/* Expand builtin macro env!(), which inspects an environment variable at + compile time. */ + +AST::ASTFragment +MacroBuiltin::env (Location invoc_locus, AST::MacroInvocData &invoc) +{ + auto invoc_token_tree = invoc.get_delim_tok_tree (); + MacroInvocLexer lex (invoc_token_tree.to_token_stream ()); + Parser parser (lex); + + auto last_token_id = macro_end_token (invoc_token_tree, parser); + + if (parser.peek_current_token ()->get_id () != STRING_LITERAL) + { + if (parser.peek_current_token ()->get_id () == last_token_id) + rust_error_at (invoc_locus, "env! takes 1 or 2 arguments"); + else + rust_error_at (parser.peek_current_token ()->get_locus (), + "argument must be a string literal"); + return AST::ASTFragment::create_error (); + } + + auto lit_expr = parser.parse_literal_expr (); + auto comma_skipped = parser.maybe_skip_token (COMMA); + + std::unique_ptr error_expr = nullptr; + + if (parser.peek_current_token ()->get_id () != last_token_id) + { + if (!comma_skipped) + { + rust_error_at (parser.peek_current_token ()->get_locus (), + "expected token: %<,%>"); + return AST::ASTFragment::create_error (); + } + if (parser.peek_current_token ()->get_id () != STRING_LITERAL) + { + rust_error_at (parser.peek_current_token ()->get_locus (), + "argument must be a string literal"); + return AST::ASTFragment::create_error (); + } + + error_expr = parser.parse_literal_expr (); + parser.maybe_skip_token (COMMA); + } + + if (parser.peek_current_token ()->get_id () != last_token_id) + { + rust_error_at (invoc_locus, "env! takes 1 or 2 arguments"); + return AST::ASTFragment::create_error (); + } + + parser.skip_token (last_token_id); + + auto env_value = getenv (lit_expr->as_string ().c_str ()); + + if (env_value == nullptr) + { + if (error_expr == nullptr) + rust_error_at (invoc_locus, "environment variable %qs not defined", + lit_expr->as_string ().c_str ()); + else + rust_error_at (invoc_locus, "%s", error_expr->as_string ().c_str ()); + return AST::ASTFragment::create_error (); + } + + auto node = AST::SingleASTNode (make_string (invoc_locus, env_value)); + return AST::ASTFragment ({node}); +} + +AST::ASTFragment +MacroBuiltin::cfg (Location invoc_locus, AST::MacroInvocData &invoc) +{ + // only parse if not already parsed + if (!invoc.is_parsed ()) + { + std::unique_ptr converted_input ( + invoc.get_delim_tok_tree ().parse_to_meta_item ()); + + if (converted_input == nullptr) + { + rust_debug ("DEBUG: failed to parse macro to meta item"); + // TODO: do something now? is this an actual error? + } + else + { + std::vector> meta_items ( + std::move (converted_input->get_items ())); + invoc.set_meta_item_output (std::move (meta_items)); + } + } + + /* TODO: assuming that cfg! macros can only have one meta item inner, like cfg + * attributes */ + if (invoc.get_meta_items ().size () != 1) + return AST::ASTFragment::create_error (); + + bool result = invoc.get_meta_items ()[0]->check_cfg_predicate ( + Session::get_instance ()); + auto literal_exp = AST::SingleASTNode (std::unique_ptr ( + new AST::LiteralExpr (result ? "true" : "false", AST::Literal::BOOL, + PrimitiveCoreType::CORETYPE_BOOL, {}, invoc_locus))); + + return AST::ASTFragment ({literal_exp}); +} + +/* Expand builtin macro include!(), which includes a source file at the current + scope compile time. */ + +AST::ASTFragment +MacroBuiltin::include (Location invoc_locus, AST::MacroInvocData &invoc) +{ + /* Get target filename from the macro invocation, which is treated as a path + relative to the include!-ing file (currently being compiled). */ + auto lit_expr + = parse_single_string_literal (invoc.get_delim_tok_tree (), invoc_locus); + if (lit_expr == nullptr) + return AST::ASTFragment::create_error (); + + std::string filename + = source_relative_path (lit_expr->as_string (), invoc_locus); + auto target_filename + = Rust::Session::get_instance ().include_extra_file (std::move (filename)); + + RAIIFile target_file (target_filename); + Linemap *linemap = Session::get_instance ().linemap; + + if (!target_file.ok ()) + { + rust_error_at (lit_expr->get_locus (), + "cannot open included file %qs: %m", target_filename); + return AST::ASTFragment::create_error (); + } + + rust_debug ("Attempting to parse included file %s", target_filename); + + Lexer lex (target_filename, std::move (target_file), linemap); + Parser parser (lex); + + auto parsed_items = parser.parse_items (); + bool has_error = !parser.get_errors ().empty (); + + for (const auto &error : parser.get_errors ()) + error.emit_error (); + + if (has_error) + { + // inform the user that the errors above are from a included file + rust_inform (invoc_locus, "included from here"); + return AST::ASTFragment::create_error (); + } + + std::vector nodes{}; + for (auto &item : parsed_items) + { + AST::SingleASTNode node (std::move (item)); + nodes.push_back (node); + } + + return AST::ASTFragment (nodes); +} + +AST::ASTFragment +MacroBuiltin::line (Location invoc_locus, AST::MacroInvocData &invoc) +{ + auto current_line + = Session::get_instance ().linemap->location_to_line (invoc_locus); + + auto line_no = AST::SingleASTNode (std::unique_ptr ( + new AST::LiteralExpr (std::to_string (current_line), AST::Literal::INT, + PrimitiveCoreType::CORETYPE_U32, {}, invoc_locus))); + + return AST::ASTFragment ({line_no}); +} + +} // namespace Rust diff --git a/gcc/rust/expand/rust-macro-builtins.h b/gcc/rust/expand/rust-macro-builtins.h new file mode 100644 index 00000000000..91f3727d450 --- /dev/null +++ b/gcc/rust/expand/rust-macro-builtins.h @@ -0,0 +1,107 @@ +// Copyright (C) 2020-2022 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 +// . + +#ifndef RUST_MACRO_BUILTINS_H +#define RUST_MACRO_BUILTINS_H + +#include "rust-ast.h" +#include "rust-location.h" + +/** + * This class provides a list of builtin macros implemented by the compiler. + * The functions defined are called "builtin transcribers" in that they replace + * the transcribing part of a macro definition. + * + * Like regular macro transcribers, they are responsible for building and + * returning an AST fragment: basically a vector of AST nodes put together. + * + * Unlike regular declarative macros where each match arm has its own associated + * transcriber, builtin transcribers are responsible for handling all match arms + * of the macro. This means that you should take extra care when implementing a + * builtin containing multiple match arms: You will probably need to do some + * lookahead in order to determine which match arm the user intended to use. + * + * An example of this is the `assert!()` macro: + * + * ``` + * macro_rules! assert { + * ($cond:expr $(,)?) => {{ ... }}; + * ($cond : expr, $ ($arg : tt) +) = > {{ ... }}; + * } + * ``` + * + * If more tokens exist beyond the optional comma, they need to be handled as + * a token-tree for a custom panic message. + * + * These builtin macros with empty transcribers are defined in the standard + * library. They are marked with a special attribute, `#[rustc_builtin_macro]`. + * When this attribute is present on a macro definition, the compiler should + * look for an associated transcriber in the mappings. Meaning that you must + * remember to insert your transcriber in the `builtin_macros` map of the + *`Mappings`. + * + * This map is built as a static variable in the `insert_macro_def()` method + * of the `Mappings` class. + */ + +/* If assert is defined as a macro this file will not parse, so undefine this + before continuing. */ +#ifdef assert +#undef assert +#endif + +namespace Rust { +class MacroBuiltin +{ +public: + static AST::ASTFragment assert (Location invoc_locus, + AST::MacroInvocData &invoc); + + static AST::ASTFragment file (Location invoc_locus, + AST::MacroInvocData &invoc); + + static AST::ASTFragment column (Location invoc_locus, + AST::MacroInvocData &invoc); + + static AST::ASTFragment include_bytes (Location invoc_locus, + AST::MacroInvocData &invoc); + + static AST::ASTFragment include_str (Location invoc_locus, + AST::MacroInvocData &invoc); + + static AST::ASTFragment compile_error (Location invoc_locus, + AST::MacroInvocData &invoc); + + static AST::ASTFragment concat (Location invoc_locus, + AST::MacroInvocData &invoc); + + static AST::ASTFragment env (Location invoc_locus, + AST::MacroInvocData &invoc); + + static AST::ASTFragment cfg (Location invoc_locus, + AST::MacroInvocData &invoc); + + static AST::ASTFragment include (Location invoc_locus, + AST::MacroInvocData &invoc); + + static AST::ASTFragment line (Location invoc_locus, + AST::MacroInvocData &invoc); +}; +} // namespace Rust + +#endif // RUST_MACRO_BUILTINS_H diff --git a/gcc/rust/expand/rust-macro-expand.cc b/gcc/rust/expand/rust-macro-expand.cc new file mode 100644 index 00000000000..1d57e394220 --- /dev/null +++ b/gcc/rust/expand/rust-macro-expand.cc @@ -0,0 +1,1012 @@ +// Copyright (C) 2020-2022 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 +// . + +#include "rust-macro-expand.h" +#include "rust-macro-substitute-ctx.h" +#include "rust-ast-full.h" +#include "rust-ast-visitor.h" +#include "rust-diagnostics.h" +#include "rust-parse.h" +#include "rust-attribute-visitor.h" + +namespace Rust { +AST::ASTFragment +MacroExpander::expand_decl_macro (Location invoc_locus, + AST::MacroInvocData &invoc, + AST::MacroRulesDefinition &rules_def, + bool semicolon) +{ + // ensure that both invocation and rules are in a valid state + rust_assert (!invoc.is_marked_for_strip ()); + rust_assert (!rules_def.is_marked_for_strip ()); + rust_assert (rules_def.get_macro_rules ().size () > 0); + + /* probably something here about parsing invoc and rules def token trees to + * token stream. if not, how would parser handle the captures of exprs and + * stuff? on the other hand, token trees may be kind of useful in rules def as + * creating a point where recursion can occur (like having + * "compare_macro_match" and then it calling itself when it finds delimiters) + */ + + /* find matching rule to invoc token tree, based on macro rule's matcher. if + * none exist, error. + * - specifically, check each matcher in order. if one fails to match, move + * onto next. */ + /* TODO: does doing this require parsing expressions and whatever in the + * invoc? if so, might as well save the results if referenced using $ or + * whatever. If not, do another pass saving them. Except this is probably + * useless as different rules could have different starting points for exprs + * or whatever. Decision trees could avoid this, but they have their own + * issues. */ + /* TODO: will need to modify the parser so that it can essentially "catch" + * errors - maybe "try_parse_expr" or whatever methods. */ + // this technically creates a back-tracking parser - this will be the + // implementation style + + /* then, after results are saved, generate the macro output from the + * transcriber token tree. if i understand this correctly, the macro + * invocation gets replaced by the transcriber tokens, except with + * substitutions made (e.g. for $i variables) */ + + /* TODO: it is probably better to modify AST::Token to store a pointer to a + * Lexer::Token (rather than being converted) - i.e. not so much have + * AST::Token as a Token but rather a TokenContainer (as it is another type of + * TokenTree). This will prevent re-conversion of Tokens between each type + * all the time, while still allowing the heterogenous storage of token trees. + */ + + AST::DelimTokenTree &invoc_token_tree = invoc.get_delim_tok_tree (); + + // find matching arm + AST::MacroRule *matched_rule = nullptr; + std::map matched_fragments; + for (auto &rule : rules_def.get_rules ()) + { + sub_stack.push (); + bool did_match_rule = try_match_rule (rule, invoc_token_tree); + matched_fragments = sub_stack.pop (); + + if (did_match_rule) + { + // // Debugging + // for (auto &kv : matched_fragments) + // rust_debug ("[fragment]: %s (%ld - %s)", kv.first.c_str (), + // kv.second.get_fragments ().size (), + // kv.second.get_kind () + // == MatchedFragmentContainer::Kind::Repetition + // ? "repetition" + // : "metavar"); + + matched_rule = &rule; + break; + } + } + + if (matched_rule == nullptr) + { + RichLocation r (invoc_locus); + r.add_range (rules_def.get_locus ()); + rust_error_at (r, "Failed to match any rule within macro"); + return AST::ASTFragment::create_error (); + } + + return transcribe_rule (*matched_rule, invoc_token_tree, matched_fragments, + semicolon, peek_context ()); +} + +void +MacroExpander::expand_invoc (AST::MacroInvocation &invoc, bool has_semicolon) +{ + if (depth_exceeds_recursion_limit ()) + { + rust_error_at (invoc.get_locus (), "reached recursion limit"); + return; + } + + AST::MacroInvocData &invoc_data = invoc.get_invoc_data (); + + // ?? + // switch on type of macro: + // - '!' syntax macro (inner switch) + // - procedural macro - "A token-based function-like macro" + // - 'macro_rules' (by example/pattern-match) macro? or not? "an + // AST-based function-like macro" + // - else is unreachable + // - attribute syntax macro (inner switch) + // - procedural macro attribute syntax - "A token-based attribute + // macro" + // - legacy macro attribute syntax? - "an AST-based attribute macro" + // - non-macro attribute: mark known + // - else is unreachable + // - derive macro (inner switch) + // - derive or legacy derive - "token-based" vs "AST-based" + // - else is unreachable + // - derive container macro - unreachable + + // lookup the rules for this macro + NodeId resolved_node = UNKNOWN_NODEID; + NodeId source_node = UNKNOWN_NODEID; + if (has_semicolon) + source_node = invoc.get_macro_node_id (); + else + source_node = invoc.get_pattern_node_id (); + auto seg + = Resolver::CanonicalPath::new_seg (source_node, + invoc_data.get_path ().as_string ()); + + bool found = resolver->get_macro_scope ().lookup (seg, &resolved_node); + if (!found) + { + rust_error_at (invoc.get_locus (), "unknown macro: [%s]", + seg.get ().c_str ()); + return; + } + + // lookup the rules + AST::MacroRulesDefinition *rules_def = nullptr; + bool ok = mappings->lookup_macro_def (resolved_node, &rules_def); + rust_assert (ok); + + auto fragment = AST::ASTFragment::create_error (); + + if (rules_def->is_builtin ()) + fragment + = rules_def->get_builtin_transcriber () (invoc.get_locus (), invoc_data); + else + fragment = expand_decl_macro (invoc.get_locus (), invoc_data, *rules_def, + has_semicolon); + + set_expanded_fragment (std::move (fragment)); +} + +/* Determines whether any cfg predicate is false and hence item with attributes + * should be stripped. Note that attributes must be expanded before calling. */ +bool +MacroExpander::fails_cfg (const AST::AttrVec &attrs) const +{ + for (const auto &attr : attrs) + { + if (attr.get_path () == "cfg" && !attr.check_cfg_predicate (session)) + return true; + } + return false; +} + +/* Determines whether any cfg predicate is false and hence item with attributes + * should be stripped. Will expand attributes as well. */ +bool +MacroExpander::fails_cfg_with_expand (AST::AttrVec &attrs) const +{ + // TODO: maybe have something that strips cfg attributes that evaluate true? + for (auto &attr : attrs) + { + if (attr.get_path () == "cfg") + { + if (!attr.is_parsed_to_meta_item ()) + attr.parse_attr_to_meta_item (); + + // DEBUG + if (!attr.is_parsed_to_meta_item ()) + rust_debug ("failed to parse attr to meta item, right before " + "cfg predicate check"); + else + rust_debug ("attr has been successfully parsed to meta item, " + "right before cfg predicate check"); + + if (!attr.check_cfg_predicate (session)) + { + // DEBUG + rust_debug ( + "cfg predicate failed for attribute: \033[0;31m'%s'\033[0m", + attr.as_string ().c_str ()); + + return true; + } + else + { + // DEBUG + rust_debug ("cfg predicate succeeded for attribute: " + "\033[0;31m'%s'\033[0m", + attr.as_string ().c_str ()); + } + } + } + return false; +} + +// Expands cfg_attr attributes. +void +MacroExpander::expand_cfg_attrs (AST::AttrVec &attrs) +{ + for (std::size_t i = 0; i < attrs.size (); i++) + { + auto &attr = attrs[i]; + if (attr.get_path () == "cfg_attr") + { + if (!attr.is_parsed_to_meta_item ()) + attr.parse_attr_to_meta_item (); + + if (attr.check_cfg_predicate (session)) + { + // split off cfg_attr + AST::AttrVec new_attrs = attr.separate_cfg_attrs (); + + // remove attr from vector + attrs.erase (attrs.begin () + i); + + // add new attrs to vector + attrs.insert (attrs.begin () + i, + std::make_move_iterator (new_attrs.begin ()), + std::make_move_iterator (new_attrs.end ())); + } + + /* do something - if feature (first token in tree) is in fact enabled, + * make tokens listed afterwards into attributes. i.e.: for + * [cfg_attr(feature = "wow", wow1, wow2)], if "wow" is true, then add + * attributes [wow1] and [wow2] to attribute list. This can also be + * recursive, so check for expanded attributes being recursive and + * possibly recursively call the expand_attrs? */ + } + else + { + i++; + } + } + attrs.shrink_to_fit (); +} + +void +MacroExpander::expand_crate () +{ + NodeId scope_node_id = crate.get_node_id (); + resolver->get_macro_scope ().push (scope_node_id); + + /* fill macro/decorator map from init list? not sure where init list comes + * from? */ + + // TODO: does cfg apply for inner attributes? research. + // the apparent answer (from playground test) is yes + + // expand crate cfg_attr attributes + expand_cfg_attrs (crate.inner_attrs); + + if (fails_cfg_with_expand (crate.inner_attrs)) + { + // basically, delete whole crate + crate.strip_crate (); + // TODO: maybe create warning here? probably not desired behaviour + } + // expand module attributes? + + push_context (ITEM); + + // expand attributes recursively and strip items if required + AttrVisitor attr_visitor (*this); + auto &items = crate.items; + for (auto it = items.begin (); it != items.end ();) + { + auto &item = *it; + + // mark for stripping if required + item->accept_vis (attr_visitor); + + auto fragment = take_expanded_fragment (attr_visitor); + if (fragment.should_expand ()) + { + // Remove the current expanded invocation + it = items.erase (it); + for (auto &node : fragment.get_nodes ()) + { + it = items.insert (it, node.take_item ()); + it++; + } + } + else if (item->is_marked_for_strip ()) + it = items.erase (it); + else + it++; + } + + pop_context (); + + // TODO: should recursive attribute and macro expansion be done in the same + // transversal? Or in separate ones like currently? + + // expand module tree recursively + + // post-process + + // extract exported macros? +} + +bool +MacroExpander::depth_exceeds_recursion_limit () const +{ + return expansion_depth >= cfg.recursion_limit; +} + +bool +MacroExpander::try_match_rule (AST::MacroRule &match_rule, + AST::DelimTokenTree &invoc_token_tree) +{ + MacroInvocLexer lex (invoc_token_tree.to_token_stream ()); + Parser parser (lex); + + AST::MacroMatcher &matcher = match_rule.get_matcher (); + + expansion_depth++; + if (!match_matcher (parser, matcher)) + { + expansion_depth--; + return false; + } + expansion_depth--; + + bool used_all_input_tokens = parser.skip_token (END_OF_FILE); + return used_all_input_tokens; +} + +bool +MacroExpander::match_fragment (Parser &parser, + AST::MacroMatchFragment &fragment) +{ + switch (fragment.get_frag_spec ().get_kind ()) + { + case AST::MacroFragSpec::EXPR: + parser.parse_expr (); + break; + + case AST::MacroFragSpec::BLOCK: + parser.parse_block_expr (); + break; + + case AST::MacroFragSpec::IDENT: + parser.parse_identifier_pattern (); + break; + + case AST::MacroFragSpec::LITERAL: + parser.parse_literal_expr (); + break; + + case AST::MacroFragSpec::ITEM: + parser.parse_item (false); + break; + + case AST::MacroFragSpec::TY: + parser.parse_type (); + break; + + case AST::MacroFragSpec::PAT: + parser.parse_pattern (); + break; + + case AST::MacroFragSpec::PATH: + parser.parse_path_in_expression (); + break; + + case AST::MacroFragSpec::VIS: + parser.parse_visibility (); + break; + + case AST::MacroFragSpec::STMT: { + auto restrictions = ParseRestrictions (); + restrictions.consume_semi = false; + parser.parse_stmt (restrictions); + break; + } + + case AST::MacroFragSpec::LIFETIME: + parser.parse_lifetime_params (); + break; + + // is meta attributes? + case AST::MacroFragSpec::META: + parser.parse_attribute_body (); + break; + + case AST::MacroFragSpec::TT: + parser.parse_token_tree (); + break; + + // i guess we just ignore invalid and just error out + case AST::MacroFragSpec::INVALID: + return false; + } + + // it matches if the parser did not produce errors trying to parse that type + // of item + return !parser.has_errors (); +} + +bool +MacroExpander::match_matcher (Parser &parser, + AST::MacroMatcher &matcher) +{ + if (depth_exceeds_recursion_limit ()) + { + rust_error_at (matcher.get_match_locus (), "reached recursion limit"); + return false; + } + + auto delimiter = parser.peek_current_token (); + + // this is used so we can check that we delimit the stream correctly. + switch (delimiter->get_id ()) + { + case LEFT_PAREN: { + if (!parser.skip_token (LEFT_PAREN)) + return false; + } + break; + + case LEFT_SQUARE: { + if (!parser.skip_token (LEFT_SQUARE)) + return false; + } + break; + + case LEFT_CURLY: { + if (!parser.skip_token (LEFT_CURLY)) + return false; + } + break; + default: + gcc_unreachable (); + } + + const MacroInvocLexer &source = parser.get_token_source (); + + for (auto &match : matcher.get_matches ()) + { + size_t offs_begin = source.get_offs (); + + switch (match->get_macro_match_type ()) + { + case AST::MacroMatch::MacroMatchType::Fragment: { + AST::MacroMatchFragment *fragment + = static_cast (match.get ()); + if (!match_fragment (parser, *fragment)) + return false; + + // matched fragment get the offset in the token stream + size_t offs_end = source.get_offs (); + sub_stack.insert_metavar ( + MatchedFragment (fragment->get_ident (), offs_begin, offs_end)); + } + break; + + case AST::MacroMatch::MacroMatchType::Tok: { + AST::Token *tok = static_cast (match.get ()); + if (!match_token (parser, *tok)) + return false; + } + break; + + case AST::MacroMatch::MacroMatchType::Repetition: { + AST::MacroMatchRepetition *rep + = static_cast (match.get ()); + if (!match_repetition (parser, *rep)) + return false; + } + break; + + case AST::MacroMatch::MacroMatchType::Matcher: { + AST::MacroMatcher *m + = static_cast (match.get ()); + expansion_depth++; + if (!match_matcher (parser, *m)) + { + expansion_depth--; + return false; + } + expansion_depth--; + } + break; + } + } + + switch (delimiter->get_id ()) + { + case LEFT_PAREN: { + if (!parser.skip_token (RIGHT_PAREN)) + return false; + } + break; + + case LEFT_SQUARE: { + if (!parser.skip_token (RIGHT_SQUARE)) + return false; + } + break; + + case LEFT_CURLY: { + if (!parser.skip_token (RIGHT_CURLY)) + return false; + } + break; + default: + gcc_unreachable (); + } + + return true; +} + +bool +MacroExpander::match_token (Parser &parser, AST::Token &token) +{ + // FIXME this needs to actually match the content and the type + return parser.skip_token (token.get_id ()); +} + +bool +MacroExpander::match_n_matches (Parser &parser, + AST::MacroMatchRepetition &rep, + size_t &match_amount, size_t lo_bound, + size_t hi_bound) +{ + match_amount = 0; + auto &matches = rep.get_matches (); + + const MacroInvocLexer &source = parser.get_token_source (); + while (true) + { + // If the current token is a closing macro delimiter, break away. + // TODO: Is this correct? + auto t_id = parser.peek_current_token ()->get_id (); + if (t_id == RIGHT_PAREN || t_id == RIGHT_SQUARE || t_id == RIGHT_CURLY) + break; + + // Skip parsing a separator on the first match, otherwise consume it. + // If it isn't present, this is an error + if (rep.has_sep () && match_amount > 0) + if (!match_token (parser, *rep.get_sep ())) + break; + + bool valid_current_match = false; + for (auto &match : matches) + { + size_t offs_begin = source.get_offs (); + switch (match->get_macro_match_type ()) + { + case AST::MacroMatch::MacroMatchType::Fragment: { + AST::MacroMatchFragment *fragment + = static_cast (match.get ()); + valid_current_match = match_fragment (parser, *fragment); + + // matched fragment get the offset in the token stream + size_t offs_end = source.get_offs (); + + // The main difference with match_matcher happens here: Instead + // of inserting a new fragment, we append to one. If that + // fragment does not exist, then the operation is similar to + // `insert_fragment` with the difference that we are not + // creating a metavariable, but a repetition of one, which is + // really different. + sub_stack.append_fragment ( + MatchedFragment (fragment->get_ident (), offs_begin, + offs_end)); + } + break; + + case AST::MacroMatch::MacroMatchType::Tok: { + AST::Token *tok = static_cast (match.get ()); + valid_current_match = match_token (parser, *tok); + } + break; + + case AST::MacroMatch::MacroMatchType::Repetition: { + AST::MacroMatchRepetition *rep + = static_cast (match.get ()); + valid_current_match = match_repetition (parser, *rep); + } + break; + + case AST::MacroMatch::MacroMatchType::Matcher: { + AST::MacroMatcher *m + = static_cast (match.get ()); + valid_current_match = match_matcher (parser, *m); + } + break; + } + } + // If we've encountered an error once, stop trying to match more + // repetitions + if (!valid_current_match) + break; + + match_amount++; + + // Break early if we notice there's too many expressions already + if (hi_bound && match_amount > hi_bound) + break; + } + + // Check if the amount of matches we got is valid: Is it more than the lower + // bound and less than the higher bound? + bool did_meet_lo_bound = match_amount >= lo_bound; + bool did_meet_hi_bound = hi_bound ? match_amount <= hi_bound : true; + + // If the end-result is valid, then we can clear the parse errors: Since + // repetitions are parsed eagerly, it is okay to fail in some cases + auto res = did_meet_lo_bound && did_meet_hi_bound; + if (res) + parser.clear_errors (); + + return res; +} + +bool +MacroExpander::match_repetition (Parser &parser, + AST::MacroMatchRepetition &rep) +{ + size_t match_amount = 0; + bool res = false; + + std::string lo_str; + std::string hi_str; + switch (rep.get_op ()) + { + case AST::MacroMatchRepetition::MacroRepOp::ANY: + lo_str = "0"; + hi_str = "+inf"; + res = match_n_matches (parser, rep, match_amount); + break; + case AST::MacroMatchRepetition::MacroRepOp::ONE_OR_MORE: + lo_str = "1"; + hi_str = "+inf"; + res = match_n_matches (parser, rep, match_amount, 1); + break; + case AST::MacroMatchRepetition::MacroRepOp::ZERO_OR_ONE: + lo_str = "0"; + hi_str = "1"; + res = match_n_matches (parser, rep, match_amount, 0, 1); + break; + default: + gcc_unreachable (); + } + + if (!res) + rust_error_at (rep.get_match_locus (), + "invalid amount of matches for macro invocation. Expected " + "between %s and %s, got %lu", + lo_str.c_str (), hi_str.c_str (), + (unsigned long) match_amount); + + rust_debug_loc (rep.get_match_locus (), "%s matched %lu times", + res ? "successfully" : "unsuccessfully", + (unsigned long) match_amount); + + // We have to handle zero fragments differently: They will not have been + // "matched" but they are still valid and should be inserted as a special + // case. So we go through the stack map, and for every fragment which doesn't + // exist, insert a zero-matched fragment. + auto &stack_map = sub_stack.peek (); + for (auto &match : rep.get_matches ()) + { + if (match->get_macro_match_type () + == AST::MacroMatch::MacroMatchType::Fragment) + { + auto fragment = static_cast (match.get ()); + auto it = stack_map.find (fragment->get_ident ()); + + if (it == stack_map.end ()) + sub_stack.insert_matches (fragment->get_ident (), + MatchedFragmentContainer::zero ()); + } + } + + return res; +} + +/** + * Helper function to refactor calling a parsing function 0 or more times + */ +static AST::ASTFragment +parse_many (Parser &parser, TokenId &delimiter, + std::function parse_fn) +{ + std::vector nodes; + while (true) + { + if (parser.peek_current_token ()->get_id () == delimiter) + break; + + auto node = parse_fn (); + nodes.emplace_back (std::move (node)); + } + + return AST::ASTFragment (std::move (nodes)); +} + +/** + * Transcribe 0 or more items from a macro invocation + * + * @param parser Parser to extract items from + * @param delimiter Id of the token on which parsing should stop + */ +static AST::ASTFragment +transcribe_many_items (Parser &parser, TokenId &delimiter) +{ + return parse_many (parser, delimiter, [&parser] () { + auto item = parser.parse_item (true); + return AST::SingleASTNode (std::move (item)); + }); +} + +/** + * Transcribe 0 or more external items from a macro invocation + * + * @param parser Parser to extract items from + * @param delimiter Id of the token on which parsing should stop + */ +static AST::ASTFragment +transcribe_many_ext (Parser &parser, TokenId &delimiter) +{ + return parse_many (parser, delimiter, [&parser] () { + auto item = parser.parse_external_item (); + return AST::SingleASTNode (std::move (item)); + }); +} + +/** + * Transcribe 0 or more trait items from a macro invocation + * + * @param parser Parser to extract items from + * @param delimiter Id of the token on which parsing should stop + */ +static AST::ASTFragment +transcribe_many_trait_items (Parser &parser, + TokenId &delimiter) +{ + return parse_many (parser, delimiter, [&parser] () { + auto item = parser.parse_trait_item (); + return AST::SingleASTNode (std::move (item)); + }); +} + +/** + * Transcribe 0 or more impl items from a macro invocation + * + * @param parser Parser to extract items from + * @param delimiter Id of the token on which parsing should stop + */ +static AST::ASTFragment +transcribe_many_impl_items (Parser &parser, TokenId &delimiter) +{ + return parse_many (parser, delimiter, [&parser] () { + auto item = parser.parse_inherent_impl_item (); + return AST::SingleASTNode (std::move (item)); + }); +} + +/** + * Transcribe 0 or more trait impl items from a macro invocation + * + * @param parser Parser to extract items from + * @param delimiter Id of the token on which parsing should stop + */ +static AST::ASTFragment +transcribe_many_trait_impl_items (Parser &parser, + TokenId &delimiter) +{ + return parse_many (parser, delimiter, [&parser] () { + auto item = parser.parse_trait_impl_item (); + return AST::SingleASTNode (std::move (item)); + }); +} + +/** + * Transcribe 0 or more statements from a macro invocation + * + * @param parser Parser to extract statements from + * @param delimiter Id of the token on which parsing should stop + */ +static AST::ASTFragment +transcribe_many_stmts (Parser &parser, TokenId &delimiter) +{ + auto restrictions = ParseRestrictions (); + restrictions.consume_semi = false; + + // FIXME: This is invalid! It needs to also handle cases where the macro + // transcriber is an expression, but since the macro call is followed by + // a semicolon, it's a valid ExprStmt + return parse_many (parser, delimiter, [&parser, restrictions] () { + auto stmt = parser.parse_stmt (restrictions); + return AST::SingleASTNode (std::move (stmt)); + }); +} + +/** + * Transcribe one expression from a macro invocation + * + * @param parser Parser to extract statements from + */ +static AST::ASTFragment +transcribe_expression (Parser &parser) +{ + auto expr = parser.parse_expr (); + + return AST::ASTFragment ({std::move (expr)}); +} + +/** + * Transcribe one type from a macro invocation + * + * @param parser Parser to extract statements from + */ +static AST::ASTFragment +transcribe_type (Parser &parser) +{ + auto type = parser.parse_type (); + + return AST::ASTFragment ({std::move (type)}); +} + +static AST::ASTFragment +transcribe_on_delimiter (Parser &parser, bool semicolon, + AST::DelimType delimiter, TokenId last_token_id) +{ + if (semicolon || delimiter == AST::DelimType::CURLY) + return transcribe_many_stmts (parser, last_token_id); + else + return transcribe_expression (parser); +} // namespace Rust + +static AST::ASTFragment +transcribe_context (MacroExpander::ContextType ctx, + Parser &parser, bool semicolon, + AST::DelimType delimiter, TokenId last_token_id) +{ + // The flow-chart in order to choose a parsing function is as follows: + // + // [switch special context] + // -- Item --> parser.parse_item(); + // -- Trait --> parser.parse_trait_item(); + // -- Impl --> parser.parse_impl_item(); + // -- Extern --> parser.parse_extern_item(); + // -- None --> [has semicolon?] + // -- Yes --> parser.parse_stmt(); + // -- No --> [switch invocation.delimiter()] + // -- { } --> parser.parse_stmt(); + // -- _ --> parser.parse_expr(); // once! + + // If there is a semicolon OR we are expanding a MacroInvocationSemi, then + // we can parse multiple items. Otherwise, parse *one* expression + + switch (ctx) + { + case MacroExpander::ContextType::ITEM: + return transcribe_many_items (parser, last_token_id); + break; + case MacroExpander::ContextType::TRAIT: + return transcribe_many_trait_items (parser, last_token_id); + break; + case MacroExpander::ContextType::IMPL: + return transcribe_many_impl_items (parser, last_token_id); + break; + case MacroExpander::ContextType::TRAIT_IMPL: + return transcribe_many_trait_impl_items (parser, last_token_id); + break; + case MacroExpander::ContextType::EXTERN: + return transcribe_many_ext (parser, last_token_id); + break; + case MacroExpander::ContextType::TYPE: + return transcribe_type (parser); + break; + default: + return transcribe_on_delimiter (parser, semicolon, delimiter, + last_token_id); + } +} + +static std::string +tokens_to_str (std::vector> &tokens) +{ + std::string str; + if (!tokens.empty ()) + { + str += tokens[0]->as_string (); + for (size_t i = 1; i < tokens.size (); i++) + str += " " + tokens[i]->as_string (); + } + + return str; +} + +AST::ASTFragment +MacroExpander::transcribe_rule ( + AST::MacroRule &match_rule, AST::DelimTokenTree &invoc_token_tree, + std::map &matched_fragments, + bool semicolon, ContextType ctx) +{ + // we can manipulate the token tree to substitute the dollar identifiers so + // that when we call parse its already substituted for us + AST::MacroTranscriber &transcriber = match_rule.get_transcriber (); + AST::DelimTokenTree &transcribe_tree = transcriber.get_token_tree (); + + auto invoc_stream = invoc_token_tree.to_token_stream (); + auto macro_rule_tokens = transcribe_tree.to_token_stream (); + + auto substitute_context + = SubstituteCtx (invoc_stream, macro_rule_tokens, matched_fragments); + std::vector> substituted_tokens + = substitute_context.substitute_tokens (); + + rust_debug ("substituted tokens: %s", + tokens_to_str (substituted_tokens).c_str ()); + + // parse it to an ASTFragment + MacroInvocLexer lex (std::move (substituted_tokens)); + Parser parser (lex); + + auto last_token_id = TokenId::RIGHT_CURLY; + + // this is used so we can check that we delimit the stream correctly. + switch (transcribe_tree.get_delim_type ()) + { + case AST::DelimType::PARENS: + last_token_id = TokenId::RIGHT_PAREN; + rust_assert (parser.skip_token (LEFT_PAREN)); + break; + + case AST::DelimType::CURLY: + rust_assert (parser.skip_token (LEFT_CURLY)); + break; + + case AST::DelimType::SQUARE: + last_token_id = TokenId::RIGHT_SQUARE; + rust_assert (parser.skip_token (LEFT_SQUARE)); + break; + } + + // see https://github.com/Rust-GCC/gccrs/issues/22 + // TL;DR: + // - Treat all macro invocations with parentheses, (), or square brackets, + // [], as expressions. + // - If the macro invocation has curly brackets, {}, it may be parsed as a + // statement depending on the context. + // - If the macro invocation has a semicolon at the end, it must be parsed + // as a statement (either via ExpressionStatement or + // MacroInvocationWithSemi) + + auto fragment + = transcribe_context (ctx, parser, semicolon, + invoc_token_tree.get_delim_type (), last_token_id); + + // emit any errors + if (parser.has_errors ()) + { + for (auto &err : parser.get_errors ()) + rust_error_at (err.locus, "%s", err.message.c_str ()); + return AST::ASTFragment::create_error (); + } + + // are all the tokens used? + bool did_delimit = parser.skip_token (last_token_id); + + bool reached_end_of_stream = did_delimit && parser.skip_token (END_OF_FILE); + if (!reached_end_of_stream) + { + const_TokenPtr current_token = parser.peek_current_token (); + rust_error_at (current_token->get_locus (), + "tokens here and after are unparsed"); + } + + return fragment; +} +} // namespace Rust diff --git a/gcc/rust/expand/rust-macro-expand.h b/gcc/rust/expand/rust-macro-expand.h new file mode 100644 index 00000000000..94d6702ecb8 --- /dev/null +++ b/gcc/rust/expand/rust-macro-expand.h @@ -0,0 +1,366 @@ +// Copyright (C) 2020-2022 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 +// . + +#ifndef RUST_MACRO_EXPAND_H +#define RUST_MACRO_EXPAND_H + +#include "rust-buffered-queue.h" +#include "rust-parse.h" +#include "rust-token.h" +#include "rust-ast.h" +#include "rust-macro.h" +#include "rust-hir-map.h" +#include "rust-name-resolver.h" +#include "rust-macro-invoc-lexer.h" + +// Provides objects and method prototypes for macro expansion + +namespace Rust { +// forward decls for AST +namespace AST { +class MacroInvocation; +} + +// Object used to store configuration data for macro expansion. +// NOTE: Keep all these items complying with the latest rustc. +struct ExpansionCfg +{ + // features? + // TODO: Add `features' when we have it. + unsigned int recursion_limit = 1024; + bool trace_mac = false; // trace macro + bool should_test = false; // strip #[test] nodes if false + bool keep_macs = false; // keep macro definitions + std::string crate_name = ""; +}; + +struct MatchedFragment +{ + std::string fragment_ident; + size_t token_offset_begin; + size_t token_offset_end; + + MatchedFragment (std::string identifier, size_t token_offset_begin, + size_t token_offset_end) + : fragment_ident (identifier), token_offset_begin (token_offset_begin), + token_offset_end (token_offset_end) + {} + + /** + * Empty constructor for uninitialized fragments + */ + MatchedFragment () : MatchedFragment ("", 0, 0) {} + + std::string as_string () const + { + return fragment_ident + "=" + std::to_string (token_offset_begin) + ":" + + std::to_string (token_offset_end); + } +}; + +class MatchedFragmentContainer +{ +public: + // Does the container refer to a simple metavariable, different from a + // repetition repeated once + enum class Kind + { + MetaVar, + Repetition, + }; + + MatchedFragmentContainer (std::vector fragments, + Kind kind = Kind::Repetition) + : fragments (fragments), kind (kind) + {} + + /** + * Create a valid fragment matched zero times. This is useful for repetitions + * which allow the absence of a fragment, such as * and ? + */ + static MatchedFragmentContainer zero () + { + return MatchedFragmentContainer ({}); + } + + /** + * Create a valid fragment matched one time + */ + static MatchedFragmentContainer metavar (MatchedFragment fragment) + { + return MatchedFragmentContainer ({fragment}, Kind::MetaVar); + } + + /** + * Add a matched fragment to the container + */ + void add_fragment (MatchedFragment fragment) + { + rust_assert (!is_single_fragment ()); + + fragments.emplace_back (fragment); + } + + size_t get_match_amount () const { return fragments.size (); } + const std::vector &get_fragments () const + { + return fragments; + } + // const std::string &get_fragment_name () const { return fragment_name; } + + bool is_single_fragment () const + { + return get_match_amount () == 1 && kind == Kind::MetaVar; + } + + const MatchedFragment get_single_fragment () const + { + rust_assert (is_single_fragment ()); + + return fragments[0]; + } + + const Kind &get_kind () const { return kind; } + +private: + /** + * Fragments matched `match_amount` times. This can be an empty vector + * in case having zero matches is allowed (i.e ? or * operators) + */ + std::vector fragments; + Kind kind; +}; + +class SubstitutionScope +{ +public: + SubstitutionScope () : stack () {} + + void push () { stack.push_back ({}); } + + std::map pop () + { + auto top = stack.back (); + stack.pop_back (); + return top; + } + + std::map &peek () + { + return stack.back (); + } + + /** + * Insert a new matched metavar into the current substitution map + */ + void insert_metavar (MatchedFragment fragment) + { + auto ¤t_map = stack.back (); + auto it = current_map.find (fragment.fragment_ident); + + if (it == current_map.end ()) + current_map.insert ({fragment.fragment_ident, + MatchedFragmentContainer::metavar (fragment)}); + else + gcc_unreachable (); + } + + /** + * Append a new matched fragment to a repetition into the current substitution + * map + */ + void append_fragment (MatchedFragment fragment) + { + auto ¤t_map = stack.back (); + auto it = current_map.find (fragment.fragment_ident); + + if (it == current_map.end ()) + current_map.insert ( + {fragment.fragment_ident, MatchedFragmentContainer ({fragment})}); + else + it->second.add_fragment (fragment); + } + + void insert_matches (std::string key, MatchedFragmentContainer matches) + { + auto ¤t_map = stack.back (); + auto it = current_map.find (key); + rust_assert (it == current_map.end ()); + + current_map.insert ({key, matches}); + } + +private: + std::vector> stack; +}; + +// Object used to store shared data (between functions) for macro expansion. +struct MacroExpander +{ + enum ContextType + { + ITEM, + BLOCK, + EXTERN, + TYPE, + TRAIT, + IMPL, + TRAIT_IMPL, + }; + + ExpansionCfg cfg; + unsigned int expansion_depth = 0; + + MacroExpander (AST::Crate &crate, ExpansionCfg cfg, Session &session) + : cfg (cfg), crate (crate), session (session), + sub_stack (SubstitutionScope ()), + expanded_fragment (AST::ASTFragment::create_error ()), + resolver (Resolver::Resolver::get ()), + mappings (Analysis::Mappings::get ()) + {} + + ~MacroExpander () = default; + + // Expands all macros in the crate passed in. + void expand_crate (); + + /* Expands a macro invocation - possibly make both + * have similar duck-typed interface and use templates?*/ + // should this be public or private? + void expand_invoc (AST::MacroInvocation &invoc, bool has_semicolon); + + // Expands a single declarative macro. + AST::ASTFragment expand_decl_macro (Location locus, + AST::MacroInvocData &invoc, + AST::MacroRulesDefinition &rules_def, + bool semicolon); + + void expand_cfg_attrs (AST::AttrVec &attrs); + bool fails_cfg (const AST::AttrVec &attr) const; + bool fails_cfg_with_expand (AST::AttrVec &attrs) const; + + bool depth_exceeds_recursion_limit () const; + + bool try_match_rule (AST::MacroRule &match_rule, + AST::DelimTokenTree &invoc_token_tree); + + AST::ASTFragment transcribe_rule ( + AST::MacroRule &match_rule, AST::DelimTokenTree &invoc_token_tree, + std::map &matched_fragments, + bool semicolon, ContextType ctx); + + bool match_fragment (Parser &parser, + AST::MacroMatchFragment &fragment); + + bool match_token (Parser &parser, AST::Token &token); + + bool match_repetition (Parser &parser, + AST::MacroMatchRepetition &rep); + + bool match_matcher (Parser &parser, + AST::MacroMatcher &matcher); + + /** + * Match any amount of matches + * + * @param parser Parser to use for matching + * @param rep Repetition to try and match + * @param match_amount Reference in which to store the ammount of succesful + * and valid matches + * + * @param lo_bound Lower bound of the matcher. When specified, the matcher + * will only succeed if it parses at *least* `lo_bound` fragments. If + * unspecified, the matcher could succeed when parsing 0 fragments. + * + * @param hi_bound Higher bound of the matcher. When specified, the matcher + * will only succeed if it parses *less than* `hi_bound` fragments. If + * unspecified, the matcher could succeed when parsing an infinity of + * fragments. + * + * @return true if matching was successful and within the given limits, false + * otherwise + */ + bool match_n_matches (Parser &parser, + AST::MacroMatchRepetition &rep, size_t &match_amount, + size_t lo_bound = 0, size_t hi_bound = 0); + + void push_context (ContextType t) { context.push_back (t); } + + ContextType pop_context () + { + rust_assert (!context.empty ()); + + ContextType t = context.back (); + context.pop_back (); + + return t; + } + + ContextType peek_context () { return context.back (); } + + void set_expanded_fragment (AST::ASTFragment &&fragment) + { + expanded_fragment = std::move (fragment); + } + + AST::ASTFragment take_expanded_fragment (AST::ASTVisitor &vis) + { + AST::ASTFragment old_fragment = std::move (expanded_fragment); + auto accumulator = std::vector (); + expanded_fragment = AST::ASTFragment::create_error (); + + for (auto &node : old_fragment.get_nodes ()) + { + expansion_depth++; + node.accept_vis (vis); + // we'll decide the next move according to the outcome of the macro + // expansion + if (expanded_fragment.is_error ()) + accumulator.push_back (node); // if expansion fails, there might be a + // non-macro expression we need to keep + else + { + // if expansion succeeded, then we need to merge the fragment with + // the contents in the accumulator, so that our final expansion + // result will contain non-macro nodes as it should + auto new_nodes = expanded_fragment.get_nodes (); + std::move (new_nodes.begin (), new_nodes.end (), + std::back_inserter (accumulator)); + expanded_fragment = AST::ASTFragment (accumulator); + } + expansion_depth--; + } + + return old_fragment; + } + +private: + AST::Crate &crate; + Session &session; + SubstitutionScope sub_stack; + std::vector context; + AST::ASTFragment expanded_fragment; + +public: + Resolver::Resolver *resolver; + Analysis::Mappings *mappings; +}; + +} // namespace Rust + +#endif diff --git a/gcc/rust/expand/rust-macro-invoc-lexer.cc b/gcc/rust/expand/rust-macro-invoc-lexer.cc new file mode 100644 index 00000000000..8a43d29e0d1 --- /dev/null +++ b/gcc/rust/expand/rust-macro-invoc-lexer.cc @@ -0,0 +1,29 @@ +#include "rust-macro-invoc-lexer.h" + +namespace Rust { + +const_TokenPtr +MacroInvocLexer::peek_token (int n) +{ + if ((offs + n) >= token_stream.size ()) + return Token::make (END_OF_FILE, Location ()); + + return token_stream.at (offs + n)->get_tok_ptr (); +} + +// Advances current token to n + 1 tokens ahead of current position. +void +MacroInvocLexer::skip_token (int n) +{ + offs += (n + 1); +} + +void +MacroInvocLexer::split_current_token (TokenId new_left __attribute__ ((unused)), + TokenId new_right + __attribute__ ((unused))) +{ + // FIXME + gcc_unreachable (); +} +} // namespace Rust diff --git a/gcc/rust/expand/rust-macro-invoc-lexer.h b/gcc/rust/expand/rust-macro-invoc-lexer.h new file mode 100644 index 00000000000..0fd4554d02f --- /dev/null +++ b/gcc/rust/expand/rust-macro-invoc-lexer.h @@ -0,0 +1,64 @@ +// Copyright (C) 2020-2022 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 +// . + +#ifndef RUST_MACRO_INVOC_LEXER_H +#define RUST_MACRO_INVOC_LEXER_H + +#include "rust-ast.h" + +namespace Rust { +class MacroInvocLexer +{ +public: + MacroInvocLexer (std::vector> stream) + : offs (0), token_stream (std::move (stream)) + {} + + // Returns token n tokens ahead of current position. + const_TokenPtr peek_token (int n); + + // Peeks the current token. + const_TokenPtr peek_token () { return peek_token (0); } + + // Advances current token to n + 1 tokens ahead of current position. + void skip_token (int n); + + // Skips the current token. + void skip_token () { skip_token (0); } + + // Splits the current token into two. Intended for use with nested generics + // closes (i.e. T> where >> is wrongly lexed as one token). Note that + // this will only work with "simple" tokens like punctuation. + void split_current_token (TokenId new_left, TokenId new_right); + + std::string get_filename () const + { + // FIXME + gcc_unreachable (); + return "FIXME"; + } + + size_t get_offs () const { return offs; } + +private: + size_t offs; + std::vector> token_stream; +}; +} // namespace Rust + +#endif // RUST_MACRO_INVOC_LEXER_H diff --git a/gcc/rust/expand/rust-macro-substitute-ctx.cc b/gcc/rust/expand/rust-macro-substitute-ctx.cc new file mode 100644 index 00000000000..9592d2d2a9e --- /dev/null +++ b/gcc/rust/expand/rust-macro-substitute-ctx.cc @@ -0,0 +1,312 @@ +#include "rust-macro-substitute-ctx.h" + +namespace Rust { + +std::vector> +SubstituteCtx::substitute_metavar (std::unique_ptr &metavar) +{ + auto metavar_name = metavar->get_str (); + + std::vector> expanded; + auto it = fragments.find (metavar_name); + if (it == fragments.end ()) + { + // Return a copy of the original token + expanded.push_back (metavar->clone_token ()); + } + else + { + // If we are expanding a metavar which has a lof of matches, we are + // currently expanding a repetition metavar - not a simple metavar. We + // need to error out and inform the user. + // Associated test case for an example: compile/macro-issue1224.rs + if (it->second.get_match_amount () != 1) + { + rust_error_at (metavar->get_locus (), + "metavariable is still repeating at this depth"); + rust_inform ( + metavar->get_locus (), + "you probably forgot the repetition operator: %<%s%s%s%>", "$(", + metavar->as_string ().c_str (), ")*"); + return expanded; + } + + // We only care about the vector when expanding repetitions. + // Just access the first element of the vector. + auto &frag = it->second.get_single_fragment (); + for (size_t offs = frag.token_offset_begin; offs < frag.token_offset_end; + offs++) + { + auto &tok = input.at (offs); + expanded.push_back (tok->clone_token ()); + } + } + + return expanded; +} + +bool +SubstituteCtx::check_repetition_amount (size_t pattern_start, + size_t pattern_end, + size_t &expected_repetition_amount) +{ + bool first_fragment_found = false; + bool is_valid = true; + + for (size_t i = pattern_start; i < pattern_end; i++) + { + if (macro.at (i)->get_id () == DOLLAR_SIGN) + { + auto &frag_token = macro.at (i + 1); + if (frag_token->get_id () == IDENTIFIER) + { + auto it = fragments.find (frag_token->get_str ()); + if (it == fragments.end ()) + { + // If the repetition is not anything we know (ie no declared + // metavars, or metavars which aren't present in the + // fragment), we can just error out. No need to paste the + // tokens as if nothing had happened. + rust_error_at (frag_token->get_locus (), + "metavar %s used in repetition does not exist", + frag_token->get_str ().c_str ()); + + is_valid = false; + } + + auto &fragment = it->second; + + size_t repeat_amount = fragment.get_match_amount (); + if (!first_fragment_found) + { + first_fragment_found = true; + expected_repetition_amount = repeat_amount; + } + else + { + if (repeat_amount != expected_repetition_amount + && !fragment.is_single_fragment ()) + { + rust_error_at ( + frag_token->get_locus (), + "different amount of matches used in merged " + "repetitions: expected %lu, got %lu", + (unsigned long) expected_repetition_amount, + (unsigned long) repeat_amount); + is_valid = false; + } + } + } + } + } + + return is_valid; +} + +std::vector> +SubstituteCtx::substitute_repetition ( + size_t pattern_start, size_t pattern_end, + std::unique_ptr separator_token) +{ + rust_assert (pattern_end < macro.size ()); + + size_t repeat_amount = 0; + if (!check_repetition_amount (pattern_start, pattern_end, repeat_amount)) + return {}; + + rust_debug ("repetition amount to use: %lu", (unsigned long) repeat_amount); + std::vector> expanded; + std::vector> new_macro; + + // We want to generate a "new macro" to substitute with. This new macro + // should contain only the tokens inside the pattern + for (size_t tok_idx = pattern_start; tok_idx < pattern_end; tok_idx++) + new_macro.emplace_back (macro.at (tok_idx)->clone_token ()); + + // Then, we want to create a subset of the matches so that + // `substitute_tokens()` can only see one fragment per metavar. Let's say we + // have the following user input: (1 145 'h') + // on the following match arm: ($($lit:literal)*) + // which causes the following matches: { "lit": [1, 145, 'h'] } + // + // The pattern (new_macro) is `$lit:literal` + // The first time we expand it, we want $lit to have the following token: 1 + // The second time, 145 + // The third and final time, 'h' + // + // In order to do so we must create "sub maps", which only contain parts of + // the original matches + // sub-maps: [ { "lit": 1 }, { "lit": 145 }, { "lit": 'h' } ] + // + // and give them to `substitute_tokens` one by one. + + for (size_t i = 0; i < repeat_amount; i++) + { + std::map sub_map; + for (auto &kv_match : fragments) + { + MatchedFragment sub_fragment; + + // FIXME: Hack: If a fragment is not repeated, how does it fit in the + // submap? Do we really want to expand it? Is this normal behavior? + if (kv_match.second.is_single_fragment ()) + sub_fragment = kv_match.second.get_single_fragment (); + else + sub_fragment = kv_match.second.get_fragments ()[i]; + + sub_map.insert ( + {kv_match.first, MatchedFragmentContainer::metavar (sub_fragment)}); + } + + auto substitute_context = SubstituteCtx (input, new_macro, sub_map); + auto new_tokens = substitute_context.substitute_tokens (); + + // Skip the first repetition, but add the separator to the expanded + // tokens if it is present + if (i != 0 && separator_token) + expanded.emplace_back (separator_token->clone_token ()); + + for (auto &new_token : new_tokens) + expanded.emplace_back (new_token->clone_token ()); + } + + // FIXME: We also need to make sure that all subsequent fragments + // contain the same amount of repetitions as the first one + + return expanded; +} + +static bool +is_rep_op (std::unique_ptr &tok) +{ + auto id = tok->get_id (); + return id == QUESTION_MARK || id == ASTERISK || id == PLUS; +} + +std::pair>, size_t> +SubstituteCtx::substitute_token (size_t token_idx) +{ + auto &token = macro.at (token_idx); + switch (token->get_id ()) + { + case IDENTIFIER: + rust_debug ("expanding metavar: %s", token->get_str ().c_str ()); + return {substitute_metavar (token), 1}; + case LEFT_PAREN: { + // We need to parse up until the closing delimiter and expand this + // fragment->n times. + rust_debug ("expanding repetition"); + + // We're in a context where macro repetitions have already been + // parsed and validated: This means that + // 1/ There will be no delimiters as that is an error + // 2/ There are no fragment specifiers anymore, which prevents us + // from reusing parser functions. + // + // Repetition patterns are also special in that they cannot contain + // "rogue" delimiters: For example, this is invalid, as they are + // parsed as MacroMatches and must contain a correct amount of + // delimiters. + // `$($e:expr ) )` + // ^ rogue closing parenthesis + // + // With all of that in mind, we can simply skip ahead from one + // parenthesis to the other to find the pattern to expand. Of course, + // pairs of delimiters, including parentheses, are allowed. + // `$($e:expr ( ) )` + // Parentheses are the sole delimiter for which we need a special + // behavior since they delimit the repetition pattern + + size_t pattern_start = token_idx + 1; + size_t pattern_end = pattern_start; + auto parentheses_stack = 0; + for (size_t idx = pattern_start; idx < macro.size (); idx++) + { + if (macro.at (idx)->get_id () == LEFT_PAREN) + { + parentheses_stack++; + } + else if (macro.at (idx)->get_id () == RIGHT_PAREN) + { + if (parentheses_stack == 0) + { + pattern_end = idx; + break; + } + parentheses_stack--; + } + } + + // Unreachable case, but let's make sure we don't ever run into it + rust_assert (pattern_end != pattern_start); + + std::unique_ptr separator_token = nullptr; + if (pattern_end + 1 <= macro.size ()) + { + auto &post_pattern_token = macro.at (pattern_end + 1); + if (!is_rep_op (post_pattern_token)) + separator_token = post_pattern_token->clone_token (); + } + + // Amount of tokens to skip + auto to_skip = 0; + // Parentheses + to_skip += 2; + // Repetition operator + to_skip += 1; + // Separator + if (separator_token) + to_skip += 1; + + return {substitute_repetition (pattern_start, pattern_end, + std::move (separator_token)), + pattern_end - pattern_start + to_skip}; + } + // TODO: We need to check if the $ was alone. In that case, do + // not error out: Simply act as if there was an empty identifier + // with no associated fragment and paste the dollar sign in the + // transcription. Unsure how to do that since we always have at + // least the closing curly brace after an empty $... + default: + rust_error_at (token->get_locus (), + "unexpected token in macro transcribe: expected " + "%<(%> or identifier after %<$%>, got %<%s%>", + get_token_description (token->get_id ())); + } + + // FIXME: gcc_unreachable() error case? + return {std::vector> (), 0}; +} + +std::vector> +SubstituteCtx::substitute_tokens () +{ + std::vector> replaced_tokens; + rust_debug ("expanding tokens"); + + for (size_t i = 0; i < macro.size (); i++) + { + auto &tok = macro.at (i); + if (tok->get_id () == DOLLAR_SIGN) + { + // Aaaaah, if only we had C++17 :) + // auto [expanded, tok_to_skip] = ... + auto p = substitute_token (i + 1); + auto expanded = std::move (p.first); + auto tok_to_skip = p.second; + + i += tok_to_skip; + + for (auto &token : expanded) + replaced_tokens.emplace_back (token->clone_token ()); + } + else + { + replaced_tokens.emplace_back (tok->clone_token ()); + } + } + + return replaced_tokens; +} + +} // namespace Rust diff --git a/gcc/rust/expand/rust-macro-substitute-ctx.h b/gcc/rust/expand/rust-macro-substitute-ctx.h new file mode 100644 index 00000000000..81dcab7643b --- /dev/null +++ b/gcc/rust/expand/rust-macro-substitute-ctx.h @@ -0,0 +1,93 @@ +// Copyright (C) 2020-2022 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 +// . + +#include "rust-ast.h" +#include "rust-macro-expand.h" + +namespace Rust { +class SubstituteCtx +{ + std::vector> &input; + std::vector> ¯o; + std::map &fragments; + + /** + * Find the repetition amount to use when expanding a repetition, and + * check that all fragments used respect that repetition amount + * + * @param pattern_start Start of the repetition pattern + * @param pattern_end End of the repetition pattern + * @param repeat_amount Reference to fill with the matched repetition amount + */ + bool check_repetition_amount (size_t pattern_start, size_t pattern_end, + size_t &repeat_amount); + +public: + SubstituteCtx (std::vector> &input, + std::vector> ¯o, + std::map &fragments) + : input (input), macro (macro), fragments (fragments) + {} + + /** + * Substitute a metavariable by its given fragment in a transcribing context, + * i.e. replacing $var with the associated fragment. + * + * @param metavar Metavariable to try and replace + * + * @return A token containing the associated fragment expanded into tokens if + * any, or the cloned token if no fragment was associated + */ + std::vector> + substitute_metavar (std::unique_ptr &metavar); + + /** + * Substitute a macro repetition by its given fragments + * + * @param pattern_start Start index of the pattern tokens + * @param pattern_end End index of the patterns tokens + * @param separator Optional separator to include when expanding tokens + * + * @return A vector containing the repeated pattern + */ + std::vector> + substitute_repetition (size_t pattern_start, size_t pattern_end, + std::unique_ptr separator); + + /** + * Substitute a given token by its appropriate representation + * + * @param token_idx Current token to try and substitute + * + * @return A token containing the associated fragment expanded into tokens if + * any, or the cloned token if no fragment was associated, as well as the + * amount of tokens that should be skipped before the next invocation. Since + * this function may consume more than just one token, it is important to skip + * ahead of the input to avoid mis-substitutions + */ + std::pair>, size_t> + substitute_token (size_t token_idx); + + /** + * Substitute all tokens by their appropriate representation + * + * @return A vector containing the substituted tokens + */ + std::vector> substitute_tokens (); +}; +} // namespace Rust From patchwork Wed Aug 24 11:59:31 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: herron.philip@googlemail.com X-Patchwork-Id: 56981 Return-Path: X-Original-To: patchwork@sourceware.org Delivered-To: patchwork@sourceware.org Received: from server2.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id BD9B0385F015 for ; Wed, 24 Aug 2022 12:01:47 +0000 (GMT) X-Original-To: gcc-patches@gcc.gnu.org Delivered-To: gcc-patches@gcc.gnu.org Received: from mail-wr1-x436.google.com (mail-wr1-x436.google.com [IPv6:2a00:1450:4864:20::436]) by sourceware.org (Postfix) with ESMTPS id EE1F93836001; Wed, 24 Aug 2022 12:00:46 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.1 sourceware.org EE1F93836001 Authentication-Results: sourceware.org; dmarc=pass (p=quarantine dis=none) header.from=googlemail.com Authentication-Results: sourceware.org; spf=pass smtp.mailfrom=googlemail.com Received: by mail-wr1-x436.google.com with SMTP id z16so1689777wrh.10; Wed, 24 Aug 2022 05:00:46 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=googlemail.com; s=20210112; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc; bh=j00CbB+sF54RFCLpvs6CiGkZ25oojrB26ggOqjGu+O8=; b=kFp4hKBevuAytb7uluMT32A4eXnI2oTNNqNZ6z24BC1iVDPWftafI3UaPSqU+Lb0G9 HTqTlJCHY/i9ER2PiadFK7mP0l8K0uk7juJIGTosfFx/8Pe2PPTvT5gxSTZgClFzeLhH R0CeyJi8FCKZ2sYvgvxEFe/NpQhlAVY5vhrQhDzTKaS5LAdqrSQ6MUtsvxYOBz3ywFdr Cd/lG7A2t/xFFnCa9yKdOvcvbLKUUDDOnNOqLnia3KDNUtH/I1F14zCgRMFOitKbgPc3 +k1UxSeG27Rfix7xHN0zbmpAVB9euaui/i5QSw1umz2YzjMDjA/11FdxLDytiGlt2wlI uk2A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=content-transfer-encoding:mime-version:reply-to:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-message-state :from:to:cc; bh=j00CbB+sF54RFCLpvs6CiGkZ25oojrB26ggOqjGu+O8=; b=Tknwibt7qMQHupYoHtr4vEpE2XSEOhyqU2Rfgjp1BADV68ftJfkRImRc4zkeneeOfn I7LKazle2YRHoXIA74yOz7cSL2g4syodTt13nhjSgt74OPlfIyVkhJn41UzyEkFN08uk 86a3YJDFB627H8iitq1ApBdhM4ODMvbp3Ac73bsebbIXn//8EWiw6OE5TQeGc6yDk35E BWp4k/com1qR4dd3oSrtOllX1aituuux8zL8eDP/lADzrOFrUdv4D7BAAGqf9WQx0QiU UlscA/1Diaxjf7gQ3wApWcJp7JVC50yRU+8E8ndS9kaR4LLTENcZ7pEPVUrYSC7LaYAt 07VA== X-Gm-Message-State: ACgBeo2yHX0dva3nFNqD8NHekhzlq6qXYXheEsIW6B//e8CPRV/YBeK+ Z1OimuFzYZ5AGKifkZoROJcV8v738zc= X-Google-Smtp-Source: AA6agR7fR5Lowm10iFhvAS2vePqY7imDSciSohTBluyZNVI2gJCyPgcJcwwAqOs0UkQ3T/krtbGQyg== X-Received: by 2002:a05:6000:697:b0:225:30e9:362b with SMTP id bo23-20020a056000069700b0022530e9362bmr15206013wrb.687.1661342444869; Wed, 24 Aug 2022 05:00:44 -0700 (PDT) Received: from localhost.localdomain ([86.14.124.218]) by smtp.gmail.com with ESMTPSA id cc19-20020a5d5c13000000b0022571d43d32sm1697676wrb.21.2022.08.24.05.00.43 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 24 Aug 2022 05:00:44 -0700 (PDT) From: herron.philip@googlemail.com X-Google-Original-From: philip.herron@embecosm.com To: gcc-patches@gcc.gnu.org Subject: [PATCH Rust front-end v2 12/37] gccrs: Add name resolution pass to the Rust front-end Date: Wed, 24 Aug 2022 12:59:31 +0100 Message-Id: <20220824115956.737931-13-philip.herron@embecosm.com> X-Mailer: git-send-email 2.25.1 In-Reply-To: <20220824115956.737931-1-philip.herron@embecosm.com> References: <20220824115956.737931-1-philip.herron@embecosm.com> MIME-Version: 1.0 X-Spam-Status: No, score=-11.5 required=5.0 tests=BAYES_00, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, DKIM_VALID_EF, FREEMAIL_FROM, GIT_PATCH_0, KAM_SHORT, RCVD_IN_DNSWL_NONE, SPF_HELO_NONE, SPF_PASS, TXREP, T_SCC_BODY_TEXT_LINE autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on server2.sourceware.org X-BeenThere: gcc-patches@gcc.gnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: Gcc-patches mailing list List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Reply-To: philip.herron@embecosm.com Cc: gcc-rust@gcc.gnu.org, Philip Herron Errors-To: gcc-patches-bounces+patchwork=sourceware.org@gcc.gnu.org Sender: "Gcc-patches" From: Philip Herron The name resolution is split into two phases, one toplevel pass which scans the whole "Crate" which iterates all items and nested items in modules to generate a context class full of CanonicalPath items. It also generates a hierarchy of parent->child and child->parent relationships using the AST NodeId for PathResolution in the second phase. The second phase drills into each item like functions and creates a stack of canonical paths for variables etc so that we can store information in a side table of usage variable 'a' resolves to NodeId '123' which refers to the NodeId of the "let a;" statement. --- gcc/rust/resolve/rust-ast-resolve-base.cc | 658 +++++++++ gcc/rust/resolve/rust-ast-resolve-base.h | 221 +++ gcc/rust/resolve/rust-ast-resolve-expr.cc | 574 ++++++++ gcc/rust/resolve/rust-ast-resolve-expr.h | 133 ++ gcc/rust/resolve/rust-ast-resolve-implitem.h | 275 ++++ gcc/rust/resolve/rust-ast-resolve-item.cc | 1237 +++++++++++++++++ gcc/rust/resolve/rust-ast-resolve-item.h | 149 ++ gcc/rust/resolve/rust-ast-resolve-path.cc | 384 +++++ gcc/rust/resolve/rust-ast-resolve-path.h | 52 + gcc/rust/resolve/rust-ast-resolve-pattern.cc | 163 +++ gcc/rust/resolve/rust-ast-resolve-pattern.h | 98 ++ gcc/rust/resolve/rust-ast-resolve-stmt.cc | 38 + gcc/rust/resolve/rust-ast-resolve-stmt.h | 378 +++++ .../rust-ast-resolve-struct-expr-field.cc | 61 + .../rust-ast-resolve-struct-expr-field.h | 55 + gcc/rust/resolve/rust-ast-resolve-toplevel.h | 460 ++++++ gcc/rust/resolve/rust-ast-resolve-type.cc | 582 ++++++++ gcc/rust/resolve/rust-ast-resolve-type.h | 290 ++++ gcc/rust/resolve/rust-ast-resolve.cc | 115 ++ gcc/rust/resolve/rust-ast-resolve.h | 50 + gcc/rust/resolve/rust-ast-verify-assignee.h | 84 ++ gcc/rust/resolve/rust-name-resolver.cc | 503 +++++++ gcc/rust/resolve/rust-name-resolver.h | 212 +++ 23 files changed, 6772 insertions(+) create mode 100644 gcc/rust/resolve/rust-ast-resolve-base.cc create mode 100644 gcc/rust/resolve/rust-ast-resolve-base.h create mode 100644 gcc/rust/resolve/rust-ast-resolve-expr.cc create mode 100644 gcc/rust/resolve/rust-ast-resolve-expr.h create mode 100644 gcc/rust/resolve/rust-ast-resolve-implitem.h create mode 100644 gcc/rust/resolve/rust-ast-resolve-item.cc create mode 100644 gcc/rust/resolve/rust-ast-resolve-item.h create mode 100644 gcc/rust/resolve/rust-ast-resolve-path.cc create mode 100644 gcc/rust/resolve/rust-ast-resolve-path.h create mode 100644 gcc/rust/resolve/rust-ast-resolve-pattern.cc create mode 100644 gcc/rust/resolve/rust-ast-resolve-pattern.h create mode 100644 gcc/rust/resolve/rust-ast-resolve-stmt.cc create mode 100644 gcc/rust/resolve/rust-ast-resolve-stmt.h create mode 100644 gcc/rust/resolve/rust-ast-resolve-struct-expr-field.cc create mode 100644 gcc/rust/resolve/rust-ast-resolve-struct-expr-field.h create mode 100644 gcc/rust/resolve/rust-ast-resolve-toplevel.h create mode 100644 gcc/rust/resolve/rust-ast-resolve-type.cc create mode 100644 gcc/rust/resolve/rust-ast-resolve-type.h create mode 100644 gcc/rust/resolve/rust-ast-resolve.cc create mode 100644 gcc/rust/resolve/rust-ast-resolve.h create mode 100644 gcc/rust/resolve/rust-ast-verify-assignee.h create mode 100644 gcc/rust/resolve/rust-name-resolver.cc create mode 100644 gcc/rust/resolve/rust-name-resolver.h diff --git a/gcc/rust/resolve/rust-ast-resolve-base.cc b/gcc/rust/resolve/rust-ast-resolve-base.cc new file mode 100644 index 00000000000..2a78918fbdb --- /dev/null +++ b/gcc/rust/resolve/rust-ast-resolve-base.cc @@ -0,0 +1,658 @@ +// Copyright (C) 2020-2022 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 +// . + +#include "rust-ast-resolve-base.h" +#include "rust-ast-resolve-expr.h" +#include "rust-ast-resolve-path.h" +#include "rust-item.h" + +namespace Rust { +namespace Resolver { + +bool +ResolverBase::resolve_visibility (const AST::Visibility &vis) +{ + if (vis.has_path ()) + { + auto path = vis.get_path (); + ResolvePath::go (&path); + + // Do we need to lookup something here? + // Is it just about resolving the names correctly so we can look them up + // later? + } + + return true; +} + +// Default visitors implementations + +void +ResolverBase::visit (AST::Token &) +{} + +void +ResolverBase::visit (AST::DelimTokenTree &) +{} + +void +ResolverBase::visit (AST::AttrInputMetaItemContainer &) +{} + +void +ResolverBase::visit (AST::IdentifierExpr &) +{} + +void +ResolverBase::visit (AST::Lifetime &) +{} + +void +ResolverBase::visit (AST::LifetimeParam &) +{} + +void +ResolverBase::visit (AST::ConstGenericParam &) +{} + +void +ResolverBase::visit (AST::PathInExpression &) +{} + +void +ResolverBase::visit (AST::TypePathSegment &) +{} + +void +ResolverBase::visit (AST::TypePathSegmentGeneric &) +{} + +void +ResolverBase::visit (AST::TypePathSegmentFunction &) +{} + +void +ResolverBase::visit (AST::TypePath &) +{} + +void +ResolverBase::visit (AST::QualifiedPathInExpression &) +{} + +void +ResolverBase::visit (AST::QualifiedPathInType &) +{} + +void +ResolverBase::visit (AST::LiteralExpr &) +{} + +void +ResolverBase::visit (AST::AttrInputLiteral &) +{} + +void +ResolverBase::visit (AST::MetaItemLitExpr &) +{} + +void +ResolverBase::visit (AST::MetaItemPathLit &) +{} + +void +ResolverBase::visit (AST::BorrowExpr &) +{} + +void +ResolverBase::visit (AST::DereferenceExpr &) +{} + +void +ResolverBase::visit (AST::ErrorPropagationExpr &) +{} + +void +ResolverBase::visit (AST::NegationExpr &) +{} + +void +ResolverBase::visit (AST::ArithmeticOrLogicalExpr &) +{} + +void +ResolverBase::visit (AST::ComparisonExpr &) +{} + +void +ResolverBase::visit (AST::LazyBooleanExpr &) +{} + +void +ResolverBase::visit (AST::TypeCastExpr &) +{} + +void +ResolverBase::visit (AST::AssignmentExpr &) +{} + +void +ResolverBase::visit (AST::CompoundAssignmentExpr &) +{} + +void +ResolverBase::visit (AST::GroupedExpr &) +{} + +void +ResolverBase::visit (AST::ArrayElemsValues &) +{} + +void +ResolverBase::visit (AST::ArrayElemsCopied &) +{} + +void +ResolverBase::visit (AST::ArrayExpr &) +{} + +void +ResolverBase::visit (AST::ArrayIndexExpr &) +{} + +void +ResolverBase::visit (AST::TupleExpr &) +{} + +void +ResolverBase::visit (AST::TupleIndexExpr &) +{} + +void +ResolverBase::visit (AST::StructExprStruct &) +{} + +void +ResolverBase::visit (AST::StructExprFieldIdentifier &) +{} + +void +ResolverBase::visit (AST::StructExprFieldIdentifierValue &) +{} + +void +ResolverBase::visit (AST::StructExprFieldIndexValue &) +{} + +void +ResolverBase::visit (AST::StructExprStructFields &) +{} + +void +ResolverBase::visit (AST::StructExprStructBase &) +{} + +void +ResolverBase::visit (AST::CallExpr &) +{} + +void +ResolverBase::visit (AST::MethodCallExpr &) +{} + +void +ResolverBase::visit (AST::FieldAccessExpr &) +{} + +void +ResolverBase::visit (AST::ClosureExprInner &) +{} + +void +ResolverBase::visit (AST::BlockExpr &) +{} + +void +ResolverBase::visit (AST::ClosureExprInnerTyped &) +{} + +void +ResolverBase::visit (AST::ContinueExpr &) +{} + +void +ResolverBase::visit (AST::BreakExpr &) +{} + +void +ResolverBase::visit (AST::RangeFromToExpr &) +{} + +void +ResolverBase::visit (AST::RangeFromExpr &) +{} + +void +ResolverBase::visit (AST::RangeToExpr &) +{} + +void +ResolverBase::visit (AST::RangeFullExpr &) +{} + +void +ResolverBase::visit (AST::RangeFromToInclExpr &) +{} + +void +ResolverBase::visit (AST::RangeToInclExpr &) +{} + +void +ResolverBase::visit (AST::ReturnExpr &) +{} + +void +ResolverBase::visit (AST::UnsafeBlockExpr &) +{} + +void +ResolverBase::visit (AST::LoopExpr &) +{} + +void +ResolverBase::visit (AST::WhileLoopExpr &) +{} + +void +ResolverBase::visit (AST::WhileLetLoopExpr &) +{} + +void +ResolverBase::visit (AST::ForLoopExpr &) +{} + +void +ResolverBase::visit (AST::IfExpr &) +{} + +void +ResolverBase::visit (AST::IfExprConseqElse &) +{} + +void +ResolverBase::visit (AST::IfExprConseqIf &) +{} + +void +ResolverBase::visit (AST::IfExprConseqIfLet &) +{} + +void +ResolverBase::visit (AST::IfLetExpr &) +{} + +void +ResolverBase::visit (AST::IfLetExprConseqElse &) +{} + +void +ResolverBase::visit (AST::IfLetExprConseqIf &) +{} + +void +ResolverBase::visit (AST::IfLetExprConseqIfLet &) +{} + +void +ResolverBase::visit (AST::MatchExpr &) +{} + +void +ResolverBase::visit (AST::AwaitExpr &) +{} + +void +ResolverBase::visit (AST::AsyncBlockExpr &) +{} + +void +ResolverBase::visit (AST::TypeParam &) +{} + +void +ResolverBase::visit (AST::LifetimeWhereClauseItem &) +{} + +void +ResolverBase::visit (AST::TypeBoundWhereClauseItem &) +{} + +void +ResolverBase::visit (AST::Method &) +{} + +void +ResolverBase::visit (AST::Module &) +{} + +void +ResolverBase::visit (AST::ExternCrate &) +{} + +void +ResolverBase::visit (AST::UseTreeGlob &) +{} + +void +ResolverBase::visit (AST::UseTreeList &) +{} + +void +ResolverBase::visit (AST::UseTreeRebind &) +{} + +void +ResolverBase::visit (AST::UseDeclaration &) +{} + +void +ResolverBase::visit (AST::Function &) +{} + +void +ResolverBase::visit (AST::TypeAlias &) +{} + +void +ResolverBase::visit (AST::StructStruct &) +{} + +void +ResolverBase::visit (AST::TupleStruct &) +{} + +void +ResolverBase::visit (AST::EnumItem &) +{} + +void +ResolverBase::visit (AST::EnumItemTuple &) +{} + +void +ResolverBase::visit (AST::EnumItemStruct &) +{} + +void +ResolverBase::visit (AST::EnumItemDiscriminant &) +{} + +void +ResolverBase::visit (AST::Enum &) +{} + +void +ResolverBase::visit (AST::Union &) +{} + +void +ResolverBase::visit (AST::ConstantItem &) +{} + +void +ResolverBase::visit (AST::StaticItem &) +{} + +void +ResolverBase::visit (AST::TraitItemFunc &) +{} + +void +ResolverBase::visit (AST::TraitItemMethod &) +{} + +void +ResolverBase::visit (AST::TraitItemConst &) +{} + +void +ResolverBase::visit (AST::TraitItemType &) +{} + +void +ResolverBase::visit (AST::Trait &) +{} + +void +ResolverBase::visit (AST::InherentImpl &) +{} + +void +ResolverBase::visit (AST::TraitImpl &) +{} + +void +ResolverBase::visit (AST::ExternalStaticItem &) +{} + +void +ResolverBase::visit (AST::ExternalFunctionItem &) +{} + +void +ResolverBase::visit (AST::ExternBlock &) +{} + +void +ResolverBase::visit (AST::MacroMatchFragment &) +{} + +void +ResolverBase::visit (AST::MacroMatchRepetition &) +{} + +void +ResolverBase::visit (AST::MacroMatcher &) +{} + +void +ResolverBase::visit (AST::MacroRulesDefinition &) +{} + +void +ResolverBase::visit (AST::MacroInvocation &) +{} + +void +ResolverBase::visit (AST::MetaItemPath &) +{} + +void +ResolverBase::visit (AST::MetaItemSeq &) +{} + +void +ResolverBase::visit (AST::MetaWord &) +{} + +void +ResolverBase::visit (AST::MetaNameValueStr &) +{} + +void +ResolverBase::visit (AST::MetaListPaths &) +{} + +void +ResolverBase::visit (AST::MetaListNameValueStr &) +{} + +void +ResolverBase::visit (AST::LiteralPattern &) +{} + +void +ResolverBase::visit (AST::IdentifierPattern &) +{} + +void +ResolverBase::visit (AST::WildcardPattern &) +{} + +void +ResolverBase::visit (AST::RangePatternBoundLiteral &) +{} + +void +ResolverBase::visit (AST::RangePatternBoundPath &) +{} + +void +ResolverBase::visit (AST::RangePatternBoundQualPath &) +{} + +void +ResolverBase::visit (AST::RangePattern &) +{} + +void +ResolverBase::visit (AST::ReferencePattern &) +{} + +void +ResolverBase::visit (AST::StructPatternFieldTuplePat &) +{} + +void +ResolverBase::visit (AST::StructPatternFieldIdentPat &) +{} + +void +ResolverBase::visit (AST::StructPatternFieldIdent &) +{} + +void +ResolverBase::visit (AST::StructPattern &) +{} + +void +ResolverBase::visit (AST::TupleStructItemsNoRange &) +{} + +void +ResolverBase::visit (AST::TupleStructItemsRange &) +{} + +void +ResolverBase::visit (AST::TupleStructPattern &) +{} + +void +ResolverBase::visit (AST::TuplePatternItemsMultiple &) +{} + +void +ResolverBase::visit (AST::TuplePatternItemsRanged &) +{} + +void +ResolverBase::visit (AST::TuplePattern &) +{} + +void +ResolverBase::visit (AST::GroupedPattern &) +{} + +void +ResolverBase::visit (AST::SlicePattern &) +{} + +void +ResolverBase::visit (AST::EmptyStmt &) +{} + +void +ResolverBase::visit (AST::LetStmt &) +{} + +void +ResolverBase::visit (AST::ExprStmtWithoutBlock &) +{} + +void +ResolverBase::visit (AST::ExprStmtWithBlock &) +{} + +void +ResolverBase::visit (AST::TraitBound &) +{} + +void +ResolverBase::visit (AST::ImplTraitType &) +{} + +void +ResolverBase::visit (AST::TraitObjectType &) +{} + +void +ResolverBase::visit (AST::ParenthesisedType &) +{} + +void +ResolverBase::visit (AST::ImplTraitTypeOneBound &) +{} + +void +ResolverBase::visit (AST::TraitObjectTypeOneBound &) +{} + +void +ResolverBase::visit (AST::TupleType &) +{} + +void +ResolverBase::visit (AST::NeverType &) +{} + +void +ResolverBase::visit (AST::RawPointerType &) +{} + +void +ResolverBase::visit (AST::ReferenceType &) +{} + +void +ResolverBase::visit (AST::ArrayType &) +{} + +void +ResolverBase::visit (AST::SliceType &) +{} + +void +ResolverBase::visit (AST::InferredType &) +{} + +void +ResolverBase::visit (AST::BareFunctionType &) +{} + +} // namespace Resolver +} // namespace Rust diff --git a/gcc/rust/resolve/rust-ast-resolve-base.h b/gcc/rust/resolve/rust-ast-resolve-base.h new file mode 100644 index 00000000000..32f30bcea62 --- /dev/null +++ b/gcc/rust/resolve/rust-ast-resolve-base.h @@ -0,0 +1,221 @@ +// Copyright (C) 2020-2022 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 +// . + +#ifndef RUST_AST_RESOLVE_BASE_H +#define RUST_AST_RESOLVE_BASE_H + +#include "rust-ast-visitor.h" +#include "rust-name-resolver.h" +#include "rust-diagnostics.h" +#include "rust-location.h" + +namespace Rust { +namespace Resolver { + +class ResolverBase : public AST::ASTVisitor +{ +public: + virtual ~ResolverBase () {} + + void visit (AST::Token &); + void visit (AST::DelimTokenTree &); + void visit (AST::AttrInputMetaItemContainer &); + void visit (AST::IdentifierExpr &); + void visit (AST::Lifetime &); + void visit (AST::LifetimeParam &); + void visit (AST::ConstGenericParam &); + void visit (AST::PathInExpression &); + void visit (AST::TypePathSegment &); + void visit (AST::TypePathSegmentGeneric &); + void visit (AST::TypePathSegmentFunction &); + void visit (AST::TypePath &); + void visit (AST::QualifiedPathInExpression &); + void visit (AST::QualifiedPathInType &); + void visit (AST::LiteralExpr &); + void visit (AST::AttrInputLiteral &); + void visit (AST::MetaItemLitExpr &); + void visit (AST::MetaItemPathLit &); + void visit (AST::BorrowExpr &); + void visit (AST::DereferenceExpr &); + void visit (AST::ErrorPropagationExpr &); + void visit (AST::NegationExpr &); + void visit (AST::ArithmeticOrLogicalExpr &); + void visit (AST::ComparisonExpr &); + void visit (AST::LazyBooleanExpr &); + void visit (AST::TypeCastExpr &); + void visit (AST::AssignmentExpr &); + void visit (AST::CompoundAssignmentExpr &); + void visit (AST::GroupedExpr &); + void visit (AST::ArrayElemsValues &); + void visit (AST::ArrayElemsCopied &); + void visit (AST::ArrayExpr &); + void visit (AST::ArrayIndexExpr &); + void visit (AST::TupleExpr &); + void visit (AST::TupleIndexExpr &); + void visit (AST::StructExprStruct &); + void visit (AST::StructExprFieldIdentifier &); + void visit (AST::StructExprFieldIdentifierValue &); + void visit (AST::StructExprFieldIndexValue &); + void visit (AST::StructExprStructFields &); + void visit (AST::StructExprStructBase &); + void visit (AST::CallExpr &); + void visit (AST::MethodCallExpr &); + void visit (AST::FieldAccessExpr &); + void visit (AST::ClosureExprInner &); + void visit (AST::BlockExpr &); + void visit (AST::ClosureExprInnerTyped &); + void visit (AST::ContinueExpr &); + void visit (AST::BreakExpr &); + void visit (AST::RangeFromToExpr &); + void visit (AST::RangeFromExpr &); + void visit (AST::RangeToExpr &); + void visit (AST::RangeFullExpr &); + void visit (AST::RangeFromToInclExpr &); + void visit (AST::RangeToInclExpr &); + void visit (AST::ReturnExpr &); + void visit (AST::UnsafeBlockExpr &); + void visit (AST::LoopExpr &); + void visit (AST::WhileLoopExpr &); + void visit (AST::WhileLetLoopExpr &); + void visit (AST::ForLoopExpr &); + void visit (AST::IfExpr &); + void visit (AST::IfExprConseqElse &); + void visit (AST::IfExprConseqIf &); + void visit (AST::IfExprConseqIfLet &); + void visit (AST::IfLetExpr &); + void visit (AST::IfLetExprConseqElse &); + void visit (AST::IfLetExprConseqIf &); + void visit (AST::IfLetExprConseqIfLet &); + + void visit (AST::MatchExpr &); + void visit (AST::AwaitExpr &); + void visit (AST::AsyncBlockExpr &); + + void visit (AST::TypeParam &); + + void visit (AST::LifetimeWhereClauseItem &); + void visit (AST::TypeBoundWhereClauseItem &); + void visit (AST::Method &); + void visit (AST::Module &); + void visit (AST::ExternCrate &); + + void visit (AST::UseTreeGlob &); + void visit (AST::UseTreeList &); + void visit (AST::UseTreeRebind &); + void visit (AST::UseDeclaration &); + void visit (AST::Function &); + void visit (AST::TypeAlias &); + void visit (AST::StructStruct &); + void visit (AST::TupleStruct &); + void visit (AST::EnumItem &); + void visit (AST::EnumItemTuple &); + void visit (AST::EnumItemStruct &); + void visit (AST::EnumItemDiscriminant &); + void visit (AST::Enum &); + void visit (AST::Union &); + void visit (AST::ConstantItem &); + void visit (AST::StaticItem &); + void visit (AST::TraitItemFunc &); + void visit (AST::TraitItemMethod &); + void visit (AST::TraitItemConst &); + void visit (AST::TraitItemType &); + void visit (AST::Trait &); + void visit (AST::InherentImpl &); + void visit (AST::TraitImpl &); + + void visit (AST::ExternalStaticItem &); + void visit (AST::ExternalFunctionItem &); + void visit (AST::ExternBlock &); + + void visit (AST::MacroMatchFragment &); + void visit (AST::MacroMatchRepetition &); + void visit (AST::MacroMatcher &); + void visit (AST::MacroRulesDefinition &); + void visit (AST::MacroInvocation &); + void visit (AST::MetaItemPath &); + void visit (AST::MetaItemSeq &); + void visit (AST::MetaWord &); + void visit (AST::MetaNameValueStr &); + void visit (AST::MetaListPaths &); + void visit (AST::MetaListNameValueStr &); + + void visit (AST::LiteralPattern &); + void visit (AST::IdentifierPattern &); + void visit (AST::WildcardPattern &); + + void visit (AST::RangePatternBoundLiteral &); + void visit (AST::RangePatternBoundPath &); + void visit (AST::RangePatternBoundQualPath &); + void visit (AST::RangePattern &); + void visit (AST::ReferencePattern &); + + void visit (AST::StructPatternFieldTuplePat &); + void visit (AST::StructPatternFieldIdentPat &); + void visit (AST::StructPatternFieldIdent &); + void visit (AST::StructPattern &); + + void visit (AST::TupleStructItemsNoRange &); + void visit (AST::TupleStructItemsRange &); + void visit (AST::TupleStructPattern &); + + void visit (AST::TuplePatternItemsMultiple &); + void visit (AST::TuplePatternItemsRanged &); + void visit (AST::TuplePattern &); + void visit (AST::GroupedPattern &); + void visit (AST::SlicePattern &); + + void visit (AST::EmptyStmt &); + void visit (AST::LetStmt &); + void visit (AST::ExprStmtWithoutBlock &); + void visit (AST::ExprStmtWithBlock &); + + void visit (AST::TraitBound &); + void visit (AST::ImplTraitType &); + void visit (AST::TraitObjectType &); + void visit (AST::ParenthesisedType &); + void visit (AST::ImplTraitTypeOneBound &); + void visit (AST::TraitObjectTypeOneBound &); + void visit (AST::TupleType &); + void visit (AST::NeverType &); + void visit (AST::RawPointerType &); + void visit (AST::ReferenceType &); + void visit (AST::ArrayType &); + void visit (AST::SliceType &); + void visit (AST::InferredType &); + void visit (AST::BareFunctionType &); + +protected: + ResolverBase () + : resolver (Resolver::get ()), mappings (Analysis::Mappings::get ()), + resolved_node (UNKNOWN_NODEID) + {} + + /** + * Resolve a visibility's path through the name resolver + */ + bool resolve_visibility (const AST::Visibility &vis); + + Resolver *resolver; + Analysis::Mappings *mappings; + NodeId resolved_node; +}; + +} // namespace Resolver +} // namespace Rust + +#endif // RUST_AST_RESOLVE_BASE_H diff --git a/gcc/rust/resolve/rust-ast-resolve-expr.cc b/gcc/rust/resolve/rust-ast-resolve-expr.cc new file mode 100644 index 00000000000..4cc4e26e3e9 --- /dev/null +++ b/gcc/rust/resolve/rust-ast-resolve-expr.cc @@ -0,0 +1,574 @@ +// Copyright (C) 2020-2022 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 +// . + +#include "rust-ast-resolve-expr.h" +#include "rust-ast-resolve-stmt.h" +#include "rust-ast-resolve-struct-expr-field.h" +#include "rust-ast-verify-assignee.h" +#include "rust-ast-resolve-type.h" +#include "rust-ast-resolve-pattern.h" +#include "rust-ast-resolve-path.h" + +namespace Rust { +namespace Resolver { + +void +ResolveExpr::go (AST::Expr *expr, const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix) +{ + ResolveExpr resolver (prefix, canonical_prefix); + expr->accept_vis (resolver); +} + +void +ResolveExpr::visit (AST::TupleIndexExpr &expr) +{ + ResolveExpr::go (expr.get_tuple_expr ().get (), prefix, canonical_prefix); +} + +void +ResolveExpr::visit (AST::TupleExpr &expr) +{ + if (expr.is_unit ()) + return; + + for (auto &elem : expr.get_tuple_elems ()) + ResolveExpr::go (elem.get (), prefix, canonical_prefix); +} + +void +ResolveExpr::visit (AST::PathInExpression &expr) +{ + ResolvePath::go (&expr); +} + +void +ResolveExpr::visit (AST::QualifiedPathInExpression &expr) +{ + ResolvePath::go (&expr); +} + +void +ResolveExpr::visit (AST::ReturnExpr &expr) +{ + if (expr.has_returned_expr ()) + ResolveExpr::go (expr.get_returned_expr ().get (), prefix, + canonical_prefix); +} + +void +ResolveExpr::visit (AST::CallExpr &expr) +{ + ResolveExpr::go (expr.get_function_expr ().get (), prefix, canonical_prefix); + for (auto ¶m : expr.get_params ()) + ResolveExpr::go (param.get (), prefix, canonical_prefix); +} + +void +ResolveExpr::visit (AST::MethodCallExpr &expr) +{ + ResolveExpr::go (expr.get_receiver_expr ().get (), prefix, canonical_prefix); + + if (expr.get_method_name ().has_generic_args ()) + { + AST::GenericArgs &args = expr.get_method_name ().get_generic_args (); + ResolveGenericArgs::go (args, prefix, canonical_prefix); + } + + auto const &in_params = expr.get_params (); + for (auto ¶m : in_params) + ResolveExpr::go (param.get (), prefix, canonical_prefix); +} + +void +ResolveExpr::visit (AST::AssignmentExpr &expr) +{ + ResolveExpr::go (expr.get_left_expr ().get (), prefix, canonical_prefix); + ResolveExpr::go (expr.get_right_expr ().get (), prefix, canonical_prefix); + + // need to verify the assignee + VerifyAsignee::go (expr.get_left_expr ().get (), expr.get_node_id ()); +} + +void +ResolveExpr::visit (AST::IdentifierExpr &expr) +{ + if (resolver->get_name_scope ().lookup ( + CanonicalPath::new_seg (expr.get_node_id (), expr.as_string ()), + &resolved_node)) + { + resolver->insert_resolved_name (expr.get_node_id (), resolved_node); + } + else if (resolver->get_type_scope ().lookup ( + CanonicalPath::new_seg (expr.get_node_id (), expr.as_string ()), + &resolved_node)) + { + resolver->insert_resolved_type (expr.get_node_id (), resolved_node); + } + else + { + rust_error_at (expr.get_locus (), "failed to find name: %s", + expr.as_string ().c_str ()); + } +} + +void +ResolveExpr::visit (AST::ArithmeticOrLogicalExpr &expr) +{ + ResolveExpr::go (expr.get_left_expr ().get (), prefix, canonical_prefix); + ResolveExpr::go (expr.get_right_expr ().get (), prefix, canonical_prefix); +} + +void +ResolveExpr::visit (AST::CompoundAssignmentExpr &expr) +{ + ResolveExpr::go (expr.get_left_expr ().get (), prefix, canonical_prefix); + ResolveExpr::go (expr.get_right_expr ().get (), prefix, canonical_prefix); + + // need to verify the assignee + VerifyAsignee::go (expr.get_left_expr ().get (), expr.get_node_id ()); +} + +void +ResolveExpr::visit (AST::ComparisonExpr &expr) +{ + ResolveExpr::go (expr.get_left_expr ().get (), prefix, canonical_prefix); + ResolveExpr::go (expr.get_right_expr ().get (), prefix, canonical_prefix); +} + +void +ResolveExpr::visit (AST::LazyBooleanExpr &expr) +{ + ResolveExpr::go (expr.get_left_expr ().get (), prefix, canonical_prefix); + ResolveExpr::go (expr.get_right_expr ().get (), prefix, canonical_prefix); +} + +void +ResolveExpr::visit (AST::NegationExpr &expr) +{ + ResolveExpr::go (expr.get_negated_expr ().get (), prefix, canonical_prefix); +} + +void +ResolveExpr::visit (AST::TypeCastExpr &expr) +{ + ResolveType::go (expr.get_type_to_cast_to ().get ()); + ResolveExpr::go (expr.get_casted_expr ().get (), prefix, canonical_prefix); +} + +void +ResolveExpr::visit (AST::IfExpr &expr) +{ + ResolveExpr::go (expr.get_condition_expr ().get (), prefix, canonical_prefix); + ResolveExpr::go (expr.get_if_block ().get (), prefix, canonical_prefix); +} + +void +ResolveExpr::visit (AST::IfExprConseqElse &expr) +{ + ResolveExpr::go (expr.get_condition_expr ().get (), prefix, canonical_prefix); + ResolveExpr::go (expr.get_if_block ().get (), prefix, canonical_prefix); + ResolveExpr::go (expr.get_else_block ().get (), prefix, canonical_prefix); +} + +void +ResolveExpr::visit (AST::IfExprConseqIf &expr) +{ + ResolveExpr::go (expr.get_condition_expr ().get (), prefix, canonical_prefix); + ResolveExpr::go (expr.get_if_block ().get (), prefix, canonical_prefix); + ResolveExpr::go (expr.get_conseq_if_expr ().get (), prefix, canonical_prefix); +} + +void +ResolveExpr::visit (AST::IfLetExpr &expr) +{ + ResolveExpr::go (expr.get_value_expr ().get (), prefix, canonical_prefix); + + NodeId scope_node_id = expr.get_node_id (); + resolver->get_name_scope ().push (scope_node_id); + resolver->get_type_scope ().push (scope_node_id); + resolver->get_label_scope ().push (scope_node_id); + resolver->push_new_name_rib (resolver->get_name_scope ().peek ()); + resolver->push_new_type_rib (resolver->get_type_scope ().peek ()); + resolver->push_new_label_rib (resolver->get_type_scope ().peek ()); + + for (auto &pattern : expr.get_patterns ()) + { + PatternDeclaration::go (pattern.get ()); + } + + ResolveExpr::go (expr.get_if_block ().get (), prefix, canonical_prefix); + + resolver->get_name_scope ().pop (); + resolver->get_type_scope ().pop (); + resolver->get_label_scope ().pop (); +} + +void +ResolveExpr::visit (AST::BlockExpr &expr) +{ + NodeId scope_node_id = expr.get_node_id (); + resolver->get_name_scope ().push (scope_node_id); + resolver->get_type_scope ().push (scope_node_id); + resolver->get_label_scope ().push (scope_node_id); + resolver->push_new_name_rib (resolver->get_name_scope ().peek ()); + resolver->push_new_type_rib (resolver->get_type_scope ().peek ()); + resolver->push_new_label_rib (resolver->get_type_scope ().peek ()); + + for (auto &s : expr.get_statements ()) + { + if (s->is_item ()) + ResolveStmt::go (s.get (), prefix, canonical_prefix, + CanonicalPath::create_empty ()); + } + + for (auto &s : expr.get_statements ()) + { + if (!s->is_item ()) + ResolveStmt::go (s.get (), prefix, canonical_prefix, + CanonicalPath::create_empty ()); + } + + if (expr.has_tail_expr ()) + ResolveExpr::go (expr.get_tail_expr ().get (), prefix, canonical_prefix); + + resolver->get_name_scope ().pop (); + resolver->get_type_scope ().pop (); + resolver->get_label_scope ().pop (); +} + +void +ResolveExpr::visit (AST::UnsafeBlockExpr &expr) +{ + expr.get_block_expr ()->accept_vis (*this); +} + +void +ResolveExpr::visit (AST::ArrayElemsValues &elems) +{ + for (auto &elem : elems.get_values ()) + ResolveExpr::go (elem.get (), prefix, canonical_prefix); +} + +void +ResolveExpr::visit (AST::ArrayExpr &expr) +{ + expr.get_array_elems ()->accept_vis (*this); +} + +void +ResolveExpr::visit (AST::ArrayIndexExpr &expr) +{ + ResolveExpr::go (expr.get_array_expr ().get (), prefix, canonical_prefix); + ResolveExpr::go (expr.get_index_expr ().get (), prefix, canonical_prefix); +} + +void +ResolveExpr::visit (AST::ArrayElemsCopied &expr) +{ + ResolveExpr::go (expr.get_num_copies ().get (), prefix, canonical_prefix); + ResolveExpr::go (expr.get_elem_to_copy ().get (), prefix, canonical_prefix); +} + +// this this an empty struct constructor like 'S {}' +void +ResolveExpr::visit (AST::StructExprStruct &struct_expr) +{ + ResolveExpr::go (&struct_expr.get_struct_name (), prefix, canonical_prefix); +} + +// this this a struct constructor with fields +void +ResolveExpr::visit (AST::StructExprStructFields &struct_expr) +{ + ResolveExpr::go (&struct_expr.get_struct_name (), prefix, canonical_prefix); + + if (struct_expr.has_struct_base ()) + { + AST::StructBase &base = struct_expr.get_struct_base (); + ResolveExpr::go (base.get_base_struct ().get (), prefix, + canonical_prefix); + } + + auto const &struct_fields = struct_expr.get_fields (); + for (auto &struct_field : struct_fields) + { + ResolveStructExprField::go (struct_field.get (), prefix, + canonical_prefix); + } +} + +void +ResolveExpr::visit (AST::GroupedExpr &expr) +{ + ResolveExpr::go (expr.get_expr_in_parens ().get (), prefix, canonical_prefix); +} + +void +ResolveExpr::visit (AST::FieldAccessExpr &expr) +{ + ResolveExpr::go (expr.get_receiver_expr ().get (), prefix, canonical_prefix); +} + +void +ResolveExpr::visit (AST::LoopExpr &expr) +{ + if (expr.has_loop_label ()) + { + auto label = expr.get_loop_label (); + if (label.get_lifetime ().get_lifetime_type () + != AST::Lifetime::LifetimeType::NAMED) + { + rust_error_at (label.get_locus (), + "Labels must be a named lifetime value"); + return; + } + + auto label_name = label.get_lifetime ().get_lifetime_name (); + auto label_lifetime_node_id = label.get_lifetime ().get_node_id (); + resolver->get_label_scope ().insert ( + CanonicalPath::new_seg (expr.get_node_id (), label_name), + label_lifetime_node_id, label.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + rust_error_at (label.get_locus (), "label redefined multiple times"); + rust_error_at (locus, "was defined here"); + }); + } + ResolveExpr::go (expr.get_loop_block ().get (), prefix, canonical_prefix); +} + +void +ResolveExpr::visit (AST::BreakExpr &expr) +{ + if (expr.has_label ()) + { + auto label = expr.get_label (); + if (label.get_lifetime_type () != AST::Lifetime::LifetimeType::NAMED) + { + rust_error_at (label.get_locus (), + "Labels must be a named lifetime value"); + return; + } + + NodeId resolved_node = UNKNOWN_NODEID; + if (!resolver->get_label_scope ().lookup ( + CanonicalPath::new_seg (label.get_node_id (), + label.get_lifetime_name ()), + &resolved_node)) + { + rust_error_at (expr.get_label ().get_locus (), + "failed to resolve label"); + return; + } + resolver->insert_resolved_label (label.get_node_id (), resolved_node); + } + + if (expr.has_break_expr ()) + ResolveExpr::go (expr.get_break_expr ().get (), prefix, canonical_prefix); +} + +void +ResolveExpr::visit (AST::WhileLoopExpr &expr) +{ + if (expr.has_loop_label ()) + { + auto label = expr.get_loop_label (); + if (label.get_lifetime ().get_lifetime_type () + != AST::Lifetime::LifetimeType::NAMED) + { + rust_error_at (label.get_locus (), + "Labels must be a named lifetime value"); + return; + } + + auto label_name = label.get_lifetime ().get_lifetime_name (); + auto label_lifetime_node_id = label.get_lifetime ().get_node_id (); + resolver->get_label_scope ().insert ( + CanonicalPath::new_seg (label.get_node_id (), label_name), + label_lifetime_node_id, label.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + rust_error_at (label.get_locus (), "label redefined multiple times"); + rust_error_at (locus, "was defined here"); + }); + } + + ResolveExpr::go (expr.get_predicate_expr ().get (), prefix, canonical_prefix); + ResolveExpr::go (expr.get_loop_block ().get (), prefix, canonical_prefix); +} + +void +ResolveExpr::visit (AST::ForLoopExpr &expr) +{ + if (expr.has_loop_label ()) + { + auto label = expr.get_loop_label (); + if (label.get_lifetime ().get_lifetime_type () + != AST::Lifetime::LifetimeType::NAMED) + { + rust_error_at (label.get_locus (), + "Labels must be a named lifetime value"); + return; + } + + auto label_name = label.get_lifetime ().get_lifetime_name (); + auto label_lifetime_node_id = label.get_lifetime ().get_node_id (); + resolver->get_label_scope ().insert ( + CanonicalPath::new_seg (label.get_node_id (), label_name), + label_lifetime_node_id, label.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + rust_error_at (label.get_locus (), "label redefined multiple times"); + rust_error_at (locus, "was defined here"); + }); + } + + // this needs a new rib to contain the pattern + NodeId scope_node_id = expr.get_node_id (); + resolver->get_name_scope ().push (scope_node_id); + resolver->get_type_scope ().push (scope_node_id); + resolver->get_label_scope ().push (scope_node_id); + resolver->push_new_name_rib (resolver->get_name_scope ().peek ()); + resolver->push_new_type_rib (resolver->get_type_scope ().peek ()); + resolver->push_new_label_rib (resolver->get_type_scope ().peek ()); + + // resolve the expression + PatternDeclaration::go (expr.get_pattern ().get ()); + ResolveExpr::go (expr.get_iterator_expr ().get (), prefix, canonical_prefix); + ResolveExpr::go (expr.get_loop_block ().get (), prefix, canonical_prefix); + + // done + resolver->get_name_scope ().pop (); + resolver->get_type_scope ().pop (); + resolver->get_label_scope ().pop (); +} + +void +ResolveExpr::visit (AST::ContinueExpr &expr) +{ + if (expr.has_label ()) + { + auto label = expr.get_label (); + if (label.get_lifetime_type () != AST::Lifetime::LifetimeType::NAMED) + { + rust_error_at (label.get_locus (), + "Labels must be a named lifetime value"); + return; + } + + NodeId resolved_node = UNKNOWN_NODEID; + if (!resolver->get_label_scope ().lookup ( + CanonicalPath::new_seg (label.get_node_id (), + label.get_lifetime_name ()), + &resolved_node)) + { + rust_error_at (expr.get_label ().get_locus (), + "failed to resolve label"); + return; + } + resolver->insert_resolved_label (label.get_node_id (), resolved_node); + } +} + +void +ResolveExpr::visit (AST::BorrowExpr &expr) +{ + ResolveExpr::go (expr.get_borrowed_expr ().get (), prefix, canonical_prefix); +} + +void +ResolveExpr::visit (AST::DereferenceExpr &expr) +{ + ResolveExpr::go (expr.get_dereferenced_expr ().get (), prefix, + canonical_prefix); +} + +void +ResolveExpr::visit (AST::MatchExpr &expr) +{ + ResolveExpr::go (expr.get_scrutinee_expr ().get (), prefix, canonical_prefix); + for (auto &match_case : expr.get_match_cases ()) + { + // each arm is in its own scope + NodeId scope_node_id = match_case.get_node_id (); + resolver->get_name_scope ().push (scope_node_id); + resolver->get_type_scope ().push (scope_node_id); + resolver->get_label_scope ().push (scope_node_id); + resolver->push_new_name_rib (resolver->get_name_scope ().peek ()); + resolver->push_new_type_rib (resolver->get_type_scope ().peek ()); + resolver->push_new_label_rib (resolver->get_type_scope ().peek ()); + + // resolve + AST::MatchArm &arm = match_case.get_arm (); + if (arm.has_match_arm_guard ()) + ResolveExpr::go (arm.get_guard_expr ().get (), prefix, + canonical_prefix); + + // insert any possible new patterns + for (auto &pattern : arm.get_patterns ()) + { + PatternDeclaration::go (pattern.get ()); + } + + // resolve the body + ResolveExpr::go (match_case.get_expr ().get (), prefix, canonical_prefix); + + // done + resolver->get_name_scope ().pop (); + resolver->get_type_scope ().pop (); + resolver->get_label_scope ().pop (); + } +} + +void +ResolveExpr::visit (AST::RangeFromToExpr &expr) +{ + ResolveExpr::go (expr.get_from_expr ().get (), prefix, canonical_prefix); + ResolveExpr::go (expr.get_to_expr ().get (), prefix, canonical_prefix); +} + +void +ResolveExpr::visit (AST::RangeFromExpr &expr) +{ + ResolveExpr::go (expr.get_from_expr ().get (), prefix, canonical_prefix); +} + +void +ResolveExpr::visit (AST::RangeToExpr &expr) +{ + ResolveExpr::go (expr.get_to_expr ().get (), prefix, canonical_prefix); +} + +void +ResolveExpr::visit (AST::RangeFullExpr &expr) +{ + // nothing to do +} + +void +ResolveExpr::visit (AST::RangeFromToInclExpr &expr) +{ + ResolveExpr::go (expr.get_from_expr ().get (), prefix, canonical_prefix); + ResolveExpr::go (expr.get_to_expr ().get (), prefix, canonical_prefix); +} + +ResolveExpr::ResolveExpr (const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix) + : ResolverBase (), prefix (prefix), canonical_prefix (canonical_prefix) +{} + +} // namespace Resolver +} // namespace Rust diff --git a/gcc/rust/resolve/rust-ast-resolve-expr.h b/gcc/rust/resolve/rust-ast-resolve-expr.h new file mode 100644 index 00000000000..11a846ac8cd --- /dev/null +++ b/gcc/rust/resolve/rust-ast-resolve-expr.h @@ -0,0 +1,133 @@ +// Copyright (C) 2020-2022 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 +// . + +#ifndef RUST_AST_RESOLVE_EXPR_H +#define RUST_AST_RESOLVE_EXPR_H + +#include "rust-ast-resolve-base.h" +#include "rust-ast-full.h" + +namespace Rust { +namespace Resolver { + +class ResolveExpr : public ResolverBase +{ + using Rust::Resolver::ResolverBase::visit; + +public: + static void go (AST::Expr *expr, const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix); + + void visit (AST::TupleIndexExpr &expr) override; + + void visit (AST::TupleExpr &expr) override; + + void visit (AST::PathInExpression &expr) override; + + void visit (AST::QualifiedPathInExpression &expr) override; + + void visit (AST::ReturnExpr &expr) override; + + void visit (AST::CallExpr &expr) override; + + void visit (AST::MethodCallExpr &expr) override; + + void visit (AST::AssignmentExpr &expr) override; + + void visit (AST::IdentifierExpr &expr) override; + + void visit (AST::ArithmeticOrLogicalExpr &expr) override; + + void visit (AST::CompoundAssignmentExpr &expr) override; + + void visit (AST::ComparisonExpr &expr) override; + + void visit (AST::LazyBooleanExpr &expr) override; + + void visit (AST::NegationExpr &expr) override; + + void visit (AST::TypeCastExpr &expr) override; + + void visit (AST::IfExpr &expr) override; + + void visit (AST::IfExprConseqElse &expr) override; + + void visit (AST::IfExprConseqIf &expr) override; + + void visit (AST::IfLetExpr &expr) override; + + void visit (AST::BlockExpr &expr) override; + + void visit (AST::UnsafeBlockExpr &expr) override; + + void visit (AST::ArrayElemsValues &elems) override; + + void visit (AST::ArrayExpr &expr) override; + + void visit (AST::ArrayIndexExpr &expr) override; + + void visit (AST::ArrayElemsCopied &elems) override; + + // this this an empty struct constructor like 'S {}' + void visit (AST::StructExprStruct &struct_expr) override; + + // this this a struct constructor with fields + void visit (AST::StructExprStructFields &struct_expr) override; + + void visit (AST::GroupedExpr &expr) override; + + void visit (AST::FieldAccessExpr &expr) override; + + void visit (AST::LoopExpr &expr) override; + + void visit (AST::BreakExpr &expr) override; + + void visit (AST::WhileLoopExpr &expr) override; + + void visit (AST::ForLoopExpr &expr) override; + + void visit (AST::ContinueExpr &expr) override; + + void visit (AST::BorrowExpr &expr) override; + + void visit (AST::DereferenceExpr &expr) override; + + void visit (AST::MatchExpr &expr) override; + + void visit (AST::RangeFromToExpr &expr) override; + + void visit (AST::RangeFromExpr &expr) override; + + void visit (AST::RangeToExpr &expr) override; + + void visit (AST::RangeFullExpr &expr) override; + + void visit (AST::RangeFromToInclExpr &expr) override; + +private: + ResolveExpr (const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix); + + const CanonicalPath &prefix; + const CanonicalPath &canonical_prefix; +}; + +} // namespace Resolver +} // namespace Rust + +#endif // RUST_AST_RESOLVE_EXPR_H diff --git a/gcc/rust/resolve/rust-ast-resolve-implitem.h b/gcc/rust/resolve/rust-ast-resolve-implitem.h new file mode 100644 index 00000000000..29dbe3436f5 --- /dev/null +++ b/gcc/rust/resolve/rust-ast-resolve-implitem.h @@ -0,0 +1,275 @@ +// Copyright (C) 2020-2022 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 +// . + +#ifndef RUST_AST_RESOLVE_IMPLITEM_H +#define RUST_AST_RESOLVE_IMPLITEM_H + +#include "rust-ast-resolve-base.h" +#include "rust-ast-resolve-type.h" +#include "rust-ast-full.h" + +namespace Rust { +namespace Resolver { + +class ResolveToplevelImplItem : public ResolverBase +{ + using Rust::Resolver::ResolverBase::visit; + +public: + static void go (AST::InherentImplItem *item, const CanonicalPath &prefix) + { + if (item->is_marked_for_strip ()) + return; + + ResolveToplevelImplItem resolver (prefix); + item->accept_vis (resolver); + } + + static void go (AST::TraitImplItem *item, const CanonicalPath &prefix) + { + if (item->is_marked_for_strip ()) + return; + + ResolveToplevelImplItem resolver (prefix); + item->accept_vis (resolver); + } + + void visit (AST::TypeAlias &type) override + { + auto decl + = CanonicalPath::new_seg (type.get_node_id (), type.get_new_type_name ()); + auto path = prefix.append (decl); + + resolver->get_type_scope ().insert ( + path, type.get_node_id (), type.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (type.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + } + + void visit (AST::ConstantItem &constant) override + { + auto decl = CanonicalPath::new_seg (constant.get_node_id (), + constant.get_identifier ()); + auto path = prefix.append (decl); + + resolver->get_name_scope ().insert ( + path, constant.get_node_id (), constant.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (constant.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + } + + void visit (AST::Function &function) override + { + auto decl = CanonicalPath::new_seg (function.get_node_id (), + function.get_function_name ()); + auto path = prefix.append (decl); + + resolver->get_name_scope ().insert ( + path, function.get_node_id (), function.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (function.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + } + + void visit (AST::Method &method) override + { + auto decl = CanonicalPath::new_seg (method.get_node_id (), + method.get_method_name ()); + auto path = prefix.append (decl); + + resolver->get_name_scope ().insert ( + path, method.get_node_id (), method.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (method.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + } + +private: + ResolveToplevelImplItem (const CanonicalPath &prefix) + : ResolverBase (), prefix (prefix) + { + rust_assert (!prefix.is_empty ()); + } + + const CanonicalPath &prefix; +}; + +class ResolveTopLevelTraitItems : public ResolverBase +{ + using Rust::Resolver::ResolverBase::visit; + +public: + static void go (AST::TraitItem *item, const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix) + { + ResolveTopLevelTraitItems resolver (prefix, canonical_prefix); + item->accept_vis (resolver); + }; + + void visit (AST::TraitItemFunc &function) override + { + auto decl = CanonicalPath::new_seg ( + function.get_node_id (), + function.get_trait_function_decl ().get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + + resolver->get_name_scope ().insert ( + path, function.get_node_id (), function.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (function.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + mappings->insert_canonical_path (function.get_node_id (), cpath); + } + + void visit (AST::TraitItemMethod &method) override + { + auto decl = CanonicalPath::new_seg ( + method.get_node_id (), method.get_trait_method_decl ().get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + + resolver->get_name_scope ().insert ( + path, method.get_node_id (), method.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (method.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + mappings->insert_canonical_path (method.get_node_id (), cpath); + } + + void visit (AST::TraitItemConst &constant) override + { + auto decl = CanonicalPath::new_seg (constant.get_node_id (), + constant.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + + resolver->get_name_scope ().insert ( + path, constant.get_node_id (), constant.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (constant.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + mappings->insert_canonical_path (constant.get_node_id (), cpath); + } + + void visit (AST::TraitItemType &type) override + { + auto decl + = CanonicalPath::new_seg (type.get_node_id (), type.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + + resolver->get_type_scope ().insert ( + path, type.get_node_id (), type.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (type.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + mappings->insert_canonical_path (type.get_node_id (), cpath); + } + +private: + ResolveTopLevelTraitItems (const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix) + : ResolverBase (), prefix (prefix), canonical_prefix (canonical_prefix) + {} + + const CanonicalPath &prefix; + const CanonicalPath &canonical_prefix; +}; + +class ResolveToplevelExternItem : public ResolverBase +{ + using Rust::Resolver::ResolverBase::visit; + +public: + static void go (AST::ExternalItem *item, const CanonicalPath &prefix) + { + ResolveToplevelExternItem resolver (prefix); + item->accept_vis (resolver); + }; + + void visit (AST::ExternalFunctionItem &function) override + { + auto decl = CanonicalPath::new_seg (function.get_node_id (), + function.get_identifier ()); + auto path = prefix.append (decl); + + resolver->get_name_scope ().insert ( + path, function.get_node_id (), function.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (function.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + NodeId current_module = resolver->peek_current_module_scope (); + mappings->insert_module_child_item (current_module, decl); + } + + void visit (AST::ExternalStaticItem &item) override + { + auto decl + = CanonicalPath::new_seg (item.get_node_id (), item.get_identifier ()); + auto path = prefix.append (decl); + + resolver->get_name_scope ().insert ( + path, item.get_node_id (), item.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (item.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + NodeId current_module = resolver->peek_current_module_scope (); + mappings->insert_module_child_item (current_module, decl); + } + +private: + ResolveToplevelExternItem (const CanonicalPath &prefix) + : ResolverBase (), prefix (prefix) + {} + + const CanonicalPath &prefix; +}; + +} // namespace Resolver +} // namespace Rust + +#endif // RUST_AST_RESOLVE_IMPLITEM_H diff --git a/gcc/rust/resolve/rust-ast-resolve-item.cc b/gcc/rust/resolve/rust-ast-resolve-item.cc new file mode 100644 index 00000000000..0c38f28d530 --- /dev/null +++ b/gcc/rust/resolve/rust-ast-resolve-item.cc @@ -0,0 +1,1237 @@ +// Copyright (C) 2020-2022 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 +// . + +#include "rust-ast-resolve-item.h" +#include "rust-ast-resolve-path.h" +#include "selftest.h" + +namespace Rust { +namespace Resolver { + +ResolveTraitItems::ResolveTraitItems (const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix) + : ResolverBase (), prefix (prefix), canonical_prefix (canonical_prefix) +{} + +void +ResolveTraitItems::go (AST::TraitItem *item, const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix) +{ + if (item->is_marked_for_strip ()) + return; + + ResolveTraitItems resolver (prefix, canonical_prefix); + item->accept_vis (resolver); +} + +void +ResolveTraitItems::visit (AST::TraitItemType &type) +{ + auto decl + = CanonicalPath::new_seg (type.get_node_id (), type.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (type.get_node_id (), cpath); + + for (auto &bound : type.get_type_param_bounds ()) + ResolveTypeBound::go (bound.get ()); +} + +void +ResolveTraitItems::visit (AST::TraitItemFunc &func) +{ + auto decl = CanonicalPath::new_seg ( + func.get_node_id (), func.get_trait_function_decl ().get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (func.get_node_id (), cpath); + + NodeId scope_node_id = func.get_node_id (); + resolver->get_name_scope ().push (scope_node_id); + resolver->get_type_scope ().push (scope_node_id); + resolver->get_label_scope ().push (scope_node_id); + resolver->push_new_name_rib (resolver->get_name_scope ().peek ()); + resolver->push_new_type_rib (resolver->get_type_scope ().peek ()); + resolver->push_new_label_rib (resolver->get_type_scope ().peek ()); + + AST::TraitFunctionDecl &function = func.get_trait_function_decl (); + if (function.has_generics ()) + for (auto &generic : function.get_generic_params ()) + ResolveGenericParam::go (generic.get (), prefix, canonical_prefix); + + if (function.has_return_type ()) + ResolveType::go (function.get_return_type ().get ()); + + // we make a new scope so the names of parameters are resolved and shadowed + // correctly + for (auto ¶m : function.get_function_params ()) + { + ResolveType::go (param.get_type ().get ()); + PatternDeclaration::go (param.get_pattern ().get ()); + } + + if (function.has_where_clause ()) + ResolveWhereClause::Resolve (function.get_where_clause ()); + + // trait items have an optional body + if (func.has_definition ()) + ResolveExpr::go (func.get_definition ().get (), path, cpath); + + resolver->get_name_scope ().pop (); + resolver->get_type_scope ().pop (); + resolver->get_label_scope ().pop (); +} + +void +ResolveTraitItems::visit (AST::TraitItemMethod &func) +{ + auto decl + = CanonicalPath::new_seg (func.get_node_id (), + func.get_trait_method_decl ().get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (func.get_node_id (), cpath); + + NodeId scope_node_id = func.get_node_id (); + resolver->get_name_scope ().push (scope_node_id); + resolver->get_type_scope ().push (scope_node_id); + resolver->get_label_scope ().push (scope_node_id); + resolver->push_new_name_rib (resolver->get_name_scope ().peek ()); + resolver->push_new_type_rib (resolver->get_type_scope ().peek ()); + resolver->push_new_label_rib (resolver->get_type_scope ().peek ()); + + AST::TraitMethodDecl &function = func.get_trait_method_decl (); + if (function.has_generics ()) + for (auto &generic : function.get_generic_params ()) + ResolveGenericParam::go (generic.get (), prefix, canonical_prefix); + + if (function.has_return_type ()) + ResolveType::go (function.get_return_type ().get ()); + + // self turns into (self: Self) as a function param + AST::SelfParam &self_param = function.get_self_param (); + AST::IdentifierPattern self_pattern (self_param.get_node_id (), "self", + self_param.get_locus (), + self_param.get_has_ref (), + self_param.get_is_mut (), + std::unique_ptr (nullptr)); + + std::vector> segments; + segments.push_back (std::unique_ptr ( + new AST::TypePathSegment ("Self", false, self_param.get_locus ()))); + + AST::TypePath self_type_path (std::move (segments), self_param.get_locus ()); + + ResolveType::go (&self_type_path); + PatternDeclaration::go (&self_pattern); + + // we make a new scope so the names of parameters are resolved and shadowed + // correctly + for (auto ¶m : function.get_function_params ()) + { + ResolveType::go (param.get_type ().get ()); + PatternDeclaration::go (param.get_pattern ().get ()); + } + + if (function.has_where_clause ()) + ResolveWhereClause::Resolve (function.get_where_clause ()); + + // trait items have an optional body + if (func.has_definition ()) + ResolveExpr::go (func.get_definition ().get (), path, cpath); + + resolver->get_name_scope ().pop (); + resolver->get_type_scope ().pop (); + resolver->get_label_scope ().pop (); +} + +void +ResolveTraitItems::visit (AST::TraitItemConst &constant) +{ + auto decl = CanonicalPath::new_seg (constant.get_node_id (), + constant.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (constant.get_node_id (), cpath); + + ResolveType::go (constant.get_type ().get ()); + + if (constant.has_expr ()) + ResolveExpr::go (constant.get_expr ().get (), path, cpath); +} + +ResolveItem::ResolveItem (const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix) + : ResolverBase (), prefix (prefix), canonical_prefix (canonical_prefix) +{} + +void +ResolveItem::go (AST::Item *item, const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix) +{ + ResolveItem resolver (prefix, canonical_prefix); + item->accept_vis (resolver); +} + +void +ResolveItem::visit (AST::TypeAlias &alias) +{ + auto talias + = CanonicalPath::new_seg (alias.get_node_id (), alias.get_new_type_name ()); + auto path = prefix.append (talias); + auto cpath = canonical_prefix.append (talias); + mappings->insert_canonical_path (alias.get_node_id (), cpath); + + NodeId scope_node_id = alias.get_node_id (); + resolver->get_type_scope ().push (scope_node_id); + + if (alias.has_generics ()) + for (auto &generic : alias.get_generic_params ()) + ResolveGenericParam::go (generic.get (), prefix, canonical_prefix); + + if (alias.has_where_clause ()) + ResolveWhereClause::Resolve (alias.get_where_clause ()); + + ResolveType::go (alias.get_type_aliased ().get ()); + + resolver->get_type_scope ().pop (); +} + +void +ResolveItem::visit (AST::Module &module) +{ + auto mod = CanonicalPath::new_seg (module.get_node_id (), module.get_name ()); + auto path = prefix.append (mod); + auto cpath = canonical_prefix.append (mod); + mappings->insert_canonical_path (module.get_node_id (), cpath); + + resolve_visibility (module.get_visibility ()); + + NodeId scope_node_id = module.get_node_id (); + resolver->get_name_scope ().push (scope_node_id); + resolver->get_type_scope ().push (scope_node_id); + resolver->get_label_scope ().push (scope_node_id); + resolver->push_new_name_rib (resolver->get_name_scope ().peek ()); + resolver->push_new_type_rib (resolver->get_type_scope ().peek ()); + resolver->push_new_label_rib (resolver->get_type_scope ().peek ()); + + // FIXME: Should we reinsert a child here? Any reason we ResolveTopLevel::go + // in ResolveTopLevel::visit (AST::Module) as well as here? + for (auto &item : module.get_items ()) + ResolveTopLevel::go (item.get (), CanonicalPath::create_empty (), cpath); + + resolver->push_new_module_scope (module.get_node_id ()); + for (auto &item : module.get_items ()) + ResolveItem::go (item.get (), path, cpath); + + resolver->pop_module_scope (); + + resolver->get_name_scope ().pop (); + resolver->get_type_scope ().pop (); + resolver->get_label_scope ().pop (); +} + +void +ResolveItem::visit (AST::TupleStruct &struct_decl) +{ + auto decl = CanonicalPath::new_seg (struct_decl.get_node_id (), + struct_decl.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (struct_decl.get_node_id (), cpath); + + resolve_visibility (struct_decl.get_visibility ()); + + NodeId scope_node_id = struct_decl.get_node_id (); + resolver->get_type_scope ().push (scope_node_id); + + if (struct_decl.has_generics ()) + for (auto &generic : struct_decl.get_generic_params ()) + ResolveGenericParam::go (generic.get (), prefix, canonical_prefix); + + if (struct_decl.has_where_clause ()) + ResolveWhereClause::Resolve (struct_decl.get_where_clause ()); + + for (AST::TupleField &field : struct_decl.get_fields ()) + { + if (field.get_field_type ()->is_marked_for_strip ()) + continue; + + resolve_visibility (field.get_visibility ()); + + ResolveType::go (field.get_field_type ().get ()); + } + + resolver->get_type_scope ().pop (); +} + +void +ResolveItem::visit (AST::Enum &enum_decl) +{ + auto decl = CanonicalPath::new_seg (enum_decl.get_node_id (), + enum_decl.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (enum_decl.get_node_id (), cpath); + + resolve_visibility (enum_decl.get_visibility ()); + + NodeId scope_node_id = enum_decl.get_node_id (); + resolver->get_type_scope ().push (scope_node_id); + + if (enum_decl.has_generics ()) + for (auto &generic : enum_decl.get_generic_params ()) + ResolveGenericParam::go (generic.get (), prefix, cpath); + + if (enum_decl.has_where_clause ()) + ResolveWhereClause::Resolve (enum_decl.get_where_clause ()); + + /* The actual fields are inside the variants. */ + for (auto &variant : enum_decl.get_variants ()) + ResolveItem::go (variant.get (), path, cpath); + + resolver->get_type_scope ().pop (); +} + +/* EnumItem doesn't need to be handled, no fields. */ +void +ResolveItem::visit (AST::EnumItem &item) +{ + // Since at this point we cannot have visibilities on enum items anymore, we + // can skip handling them + + auto decl + = CanonicalPath::new_seg (item.get_node_id (), item.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (item.get_node_id (), cpath); +} + +void +ResolveItem::visit (AST::EnumItemTuple &item) +{ + auto decl + = CanonicalPath::new_seg (item.get_node_id (), item.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (item.get_node_id (), cpath); + + for (auto &field : item.get_tuple_fields ()) + { + if (field.get_field_type ()->is_marked_for_strip ()) + continue; + + ResolveType::go (field.get_field_type ().get ()); + } +} + +void +ResolveItem::visit (AST::EnumItemStruct &item) +{ + auto decl + = CanonicalPath::new_seg (item.get_node_id (), item.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (item.get_node_id (), cpath); + + for (auto &field : item.get_struct_fields ()) + { + if (field.get_field_type ()->is_marked_for_strip ()) + continue; + + ResolveType::go (field.get_field_type ().get ()); + } +} + +void +ResolveItem::visit (AST::EnumItemDiscriminant &item) +{ + auto decl + = CanonicalPath::new_seg (item.get_node_id (), item.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + + mappings->insert_canonical_path (item.get_node_id (), cpath); +} + +void +ResolveItem::visit (AST::StructStruct &struct_decl) +{ + auto decl = CanonicalPath::new_seg (struct_decl.get_node_id (), + struct_decl.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (struct_decl.get_node_id (), cpath); + + resolve_visibility (struct_decl.get_visibility ()); + + NodeId scope_node_id = struct_decl.get_node_id (); + resolver->get_type_scope ().push (scope_node_id); + + if (struct_decl.has_generics ()) + for (auto &generic : struct_decl.get_generic_params ()) + ResolveGenericParam::go (generic.get (), prefix, canonical_prefix); + + if (struct_decl.has_where_clause ()) + ResolveWhereClause::Resolve (struct_decl.get_where_clause ()); + + for (AST::StructField &field : struct_decl.get_fields ()) + { + if (field.get_field_type ()->is_marked_for_strip ()) + continue; + + resolve_visibility (field.get_visibility ()); + + ResolveType::go (field.get_field_type ().get ()); + } + + resolver->get_type_scope ().pop (); +} + +void +ResolveItem::visit (AST::Union &union_decl) +{ + auto decl = CanonicalPath::new_seg (union_decl.get_node_id (), + union_decl.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (union_decl.get_node_id (), cpath); + + resolve_visibility (union_decl.get_visibility ()); + + NodeId scope_node_id = union_decl.get_node_id (); + resolver->get_type_scope ().push (scope_node_id); + + if (union_decl.has_generics ()) + for (auto &generic : union_decl.get_generic_params ()) + ResolveGenericParam::go (generic.get (), prefix, canonical_prefix); + + if (union_decl.has_where_clause ()) + ResolveWhereClause::Resolve (union_decl.get_where_clause ()); + + for (AST::StructField &field : union_decl.get_variants ()) + { + if (field.get_field_type ()->is_marked_for_strip ()) + continue; + + ResolveType::go (field.get_field_type ().get ()); + } + + resolver->get_type_scope ().pop (); +} + +void +ResolveItem::visit (AST::StaticItem &var) +{ + auto decl + = CanonicalPath::new_seg (var.get_node_id (), var.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (var.get_node_id (), cpath); + + ResolveType::go (var.get_type ().get ()); + ResolveExpr::go (var.get_expr ().get (), path, cpath); +} + +void +ResolveItem::visit (AST::ConstantItem &constant) +{ + auto decl = CanonicalPath::new_seg (constant.get_node_id (), + constant.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (constant.get_node_id (), cpath); + + resolve_visibility (constant.get_visibility ()); + + ResolveType::go (constant.get_type ().get ()); + ResolveExpr::go (constant.get_expr ().get (), path, cpath); +} + +void +ResolveItem::visit (AST::Function &function) +{ + auto decl = CanonicalPath::new_seg (function.get_node_id (), + function.get_function_name ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + + mappings->insert_canonical_path (function.get_node_id (), cpath); + + resolve_visibility (function.get_visibility ()); + + NodeId scope_node_id = function.get_node_id (); + resolver->get_name_scope ().push (scope_node_id); + resolver->get_type_scope ().push (scope_node_id); + resolver->get_label_scope ().push (scope_node_id); + resolver->push_new_name_rib (resolver->get_name_scope ().peek ()); + resolver->push_new_type_rib (resolver->get_type_scope ().peek ()); + resolver->push_new_label_rib (resolver->get_type_scope ().peek ()); + + if (function.has_generics ()) + for (auto &generic : function.get_generic_params ()) + ResolveGenericParam::go (generic.get (), prefix, canonical_prefix); + + // resolve any where clause items + if (function.has_where_clause ()) + ResolveWhereClause::Resolve (function.get_where_clause ()); + + if (function.has_return_type ()) + ResolveType::go (function.get_return_type ().get ()); + + // we make a new scope so the names of parameters are resolved and shadowed + // correctly + for (auto ¶m : function.get_function_params ()) + { + ResolveType::go (param.get_type ().get ()); + PatternDeclaration::go (param.get_pattern ().get ()); + + // the mutability checker needs to verify for immutable decls the number + // of assignments are <1. This marks an implicit assignment + } + + // resolve the function body + ResolveExpr::go (function.get_definition ().get (), path, cpath); + + resolver->get_name_scope ().pop (); + resolver->get_type_scope ().pop (); + resolver->get_label_scope ().pop (); +} + +void +ResolveItem::visit (AST::InherentImpl &impl_block) +{ + NodeId scope_node_id = impl_block.get_node_id (); + resolver->get_name_scope ().push (scope_node_id); + resolver->get_type_scope ().push (scope_node_id); + resolver->push_new_name_rib (resolver->get_name_scope ().peek ()); + resolver->push_new_type_rib (resolver->get_type_scope ().peek ()); + + resolve_visibility (impl_block.get_visibility ()); + + if (impl_block.has_generics ()) + for (auto &generic : impl_block.get_generic_params ()) + ResolveGenericParam::go (generic.get (), prefix, canonical_prefix); + + // resolve any where clause items + if (impl_block.has_where_clause ()) + ResolveWhereClause::Resolve (impl_block.get_where_clause ()); + + // FIXME this needs to be protected behind nominal type-checks see: + // rustc --explain E0118 + ResolveType::go (impl_block.get_type ().get ()); + + // Setup paths + CanonicalPath self_cpath = CanonicalPath::create_empty (); + bool ok = ResolveTypeToCanonicalPath::go (impl_block.get_type ().get (), + self_cpath); + rust_assert (ok); + rust_debug ("AST::InherentImpl resolve Self: {%s}", + self_cpath.get ().c_str ()); + + CanonicalPath impl_type = self_cpath; + CanonicalPath impl_prefix = prefix.append (impl_type); + + // see https://godbolt.org/z/a3vMbsT6W + CanonicalPath cpath = CanonicalPath::create_empty (); + if (canonical_prefix.size () <= 1) + { + cpath = self_cpath; + } + else + { + std::string seg_buf = ""; + CanonicalPath seg + = CanonicalPath::new_seg (impl_block.get_node_id (), seg_buf); + cpath = canonical_prefix.append (seg); + } + + // done setup paths + + auto Self + = CanonicalPath::get_big_self (impl_block.get_type ()->get_node_id ()); + + resolver->get_type_scope ().insert (Self, + impl_block.get_type ()->get_node_id (), + impl_block.get_type ()->get_locus ()); + + for (auto &impl_item : impl_block.get_impl_items ()) + { + rust_debug ( + "AST::InherentImpl resolve_impl_item: impl_prefix={%s} cpath={%s}", + impl_prefix.get ().c_str (), cpath.get ().c_str ()); + resolve_impl_item (impl_item.get (), impl_prefix, cpath); + } + + resolver->get_type_scope ().peek ()->clear_name ( + Self, impl_block.get_type ()->get_node_id ()); + + resolver->get_type_scope ().pop (); + resolver->get_name_scope ().pop (); +} + +void +ResolveItem::visit (AST::Method &method) +{ + auto decl + = CanonicalPath::new_seg (method.get_node_id (), method.get_method_name ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (method.get_node_id (), cpath); + + NodeId scope_node_id = method.get_node_id (); + + resolve_visibility (method.get_visibility ()); + + resolver->get_name_scope ().push (scope_node_id); + resolver->get_type_scope ().push (scope_node_id); + resolver->get_label_scope ().push (scope_node_id); + resolver->push_new_name_rib (resolver->get_name_scope ().peek ()); + resolver->push_new_type_rib (resolver->get_type_scope ().peek ()); + resolver->push_new_label_rib (resolver->get_type_scope ().peek ()); + + if (method.has_generics ()) + for (auto &generic : method.get_generic_params ()) + ResolveGenericParam::go (generic.get (), prefix, canonical_prefix); + + // resolve any where clause items + if (method.has_where_clause ()) + ResolveWhereClause::Resolve (method.get_where_clause ()); + + if (method.has_return_type ()) + ResolveType::go (method.get_return_type ().get ()); + + // self turns into (self: Self) as a function param + AST::SelfParam &self_param = method.get_self_param (); + AST::IdentifierPattern self_pattern (self_param.get_node_id (), "self", + self_param.get_locus (), + self_param.get_has_ref (), + self_param.get_is_mut (), + std::unique_ptr (nullptr)); + + std::vector> segments; + segments.push_back (std::unique_ptr ( + new AST::TypePathSegment ("Self", false, self_param.get_locus ()))); + + AST::TypePath self_type_path (std::move (segments), self_param.get_locus ()); + + ResolveType::go (&self_type_path); + PatternDeclaration::go (&self_pattern); + + // we make a new scope so the names of parameters are resolved and shadowed + // correctly + for (auto ¶m : method.get_function_params ()) + { + ResolveType::go (param.get_type ().get ()); + PatternDeclaration::go (param.get_pattern ().get ()); + } + + // resolve any where clause items + if (method.has_where_clause ()) + ResolveWhereClause::Resolve (method.get_where_clause ()); + + // resolve the function body + ResolveExpr::go (method.get_definition ().get (), path, cpath); + + resolver->get_name_scope ().pop (); + resolver->get_type_scope ().pop (); + resolver->get_label_scope ().pop (); +} + +void +ResolveItem::visit (AST::TraitImpl &impl_block) +{ + NodeId scope_node_id = impl_block.get_node_id (); + + resolve_visibility (impl_block.get_visibility ()); + + resolver->get_name_scope ().push (scope_node_id); + resolver->get_type_scope ().push (scope_node_id); + resolver->push_new_name_rib (resolver->get_name_scope ().peek ()); + resolver->push_new_type_rib (resolver->get_type_scope ().peek ()); + + if (impl_block.has_generics ()) + for (auto &generic : impl_block.get_generic_params ()) + ResolveGenericParam::go (generic.get (), prefix, canonical_prefix); + + // resolve any where clause items + if (impl_block.has_where_clause ()) + ResolveWhereClause::Resolve (impl_block.get_where_clause ()); + + // CanonicalPath canonical_trait_type = CanonicalPath::create_empty (); + NodeId trait_resolved_node = ResolveType::go (&impl_block.get_trait_path ()); + if (trait_resolved_node == UNKNOWN_NODEID) + { + resolver->get_type_scope ().pop (); + resolver->get_name_scope ().pop (); + return; + } + + // CanonicalPath canonical_impl_type = CanonicalPath::create_empty (); + NodeId type_resolved_node = ResolveType::go (impl_block.get_type ().get ()); + if (type_resolved_node == UNKNOWN_NODEID) + { + resolver->get_type_scope ().pop (); + resolver->get_name_scope ().pop (); + return; + } + + bool ok; + // setup paths + CanonicalPath canonical_trait_type = CanonicalPath::create_empty (); + ok = ResolveTypeToCanonicalPath::go (&impl_block.get_trait_path (), + canonical_trait_type); + rust_assert (ok); + + rust_debug ("AST::TraitImpl resolve trait type: {%s}", + canonical_trait_type.get ().c_str ()); + + CanonicalPath canonical_impl_type = CanonicalPath::create_empty (); + ok = ResolveTypeToCanonicalPath::go (impl_block.get_type ().get (), + canonical_impl_type); + rust_assert (ok); + + rust_debug ("AST::TraitImpl resolve self: {%s}", + canonical_impl_type.get ().c_str ()); + + // raw paths + CanonicalPath impl_type_seg = canonical_impl_type; + CanonicalPath trait_type_seg = canonical_trait_type; + CanonicalPath projection + = CanonicalPath::trait_impl_projection_seg (impl_block.get_node_id (), + trait_type_seg, impl_type_seg); + CanonicalPath impl_prefix = prefix.append (projection); + + // setup canonical-path + CanonicalPath canonical_projection + = CanonicalPath::trait_impl_projection_seg (impl_block.get_node_id (), + canonical_trait_type, + canonical_impl_type); + CanonicalPath cpath = CanonicalPath::create_empty (); + if (canonical_prefix.size () <= 1) + { + cpath = canonical_projection; + } + else + { + std::string projection_str = canonical_projection.get (); + std::string seg_buf + = ""; + CanonicalPath seg + = CanonicalPath::new_seg (impl_block.get_node_id (), seg_buf); + cpath = canonical_prefix.append (seg); + } + + // DONE setup canonical-path + + auto Self + = CanonicalPath::get_big_self (impl_block.get_type ()->get_node_id ()); + + resolver->get_type_scope ().insert (Self, + impl_block.get_type ()->get_node_id (), + impl_block.get_type ()->get_locus ()); + + for (auto &impl_item : impl_block.get_impl_items ()) + { + rust_debug ( + "AST::TraitImpl resolve_impl_item: impl_prefix={%s} cpath={%s}", + impl_prefix.get ().c_str (), cpath.get ().c_str ()); + resolve_impl_item (impl_item.get (), impl_prefix, cpath); + } + + resolver->get_type_scope ().peek ()->clear_name ( + Self, impl_block.get_type ()->get_node_id ()); + resolver->get_type_scope ().pop (); +} + +void +ResolveItem::visit (AST::Trait &trait) +{ + NodeId scope_node_id = trait.get_node_id (); + + resolve_visibility (trait.get_visibility ()); + + resolver->get_name_scope ().push (scope_node_id); + resolver->get_type_scope ().push (scope_node_id); + resolver->push_new_name_rib (resolver->get_name_scope ().peek ()); + resolver->push_new_type_rib (resolver->get_type_scope ().peek ()); + + // we need to inject an implicit self TypeParam here + AST::TypeParam *implicit_self + = new AST::TypeParam ("Self", trait.get_locus ()); + trait.insert_implict_self ( + std::unique_ptr (implicit_self)); + CanonicalPath Self = CanonicalPath::get_big_self (trait.get_node_id ()); + + for (auto &generic : trait.get_generic_params ()) + ResolveGenericParam::go (generic.get (), prefix, canonical_prefix); + + // Self is an implicit TypeParam so lets mark it as such + resolver->get_type_scope ().append_reference_for_def ( + Self.get_node_id (), implicit_self->get_node_id ()); + + if (trait.has_type_param_bounds ()) + { + for (auto &bound : trait.get_type_param_bounds ()) + { + ResolveTypeBound::go (bound.get ()); + } + } + + // resolve any where clause items + if (trait.has_where_clause ()) + ResolveWhereClause::Resolve (trait.get_where_clause ()); + + // resolve the paths + CanonicalPath path = CanonicalPath::create_empty (); + CanonicalPath cpath = CanonicalPath::create_empty (); + // + + for (auto &item : trait.get_trait_items ()) + { + ResolveTraitItems::go (item.get (), path, cpath); + } + + resolver->get_type_scope ().pop (); + resolver->get_name_scope ().pop (); +} + +void +ResolveItem::visit (AST::ExternBlock &extern_block) +{ + resolve_visibility (extern_block.get_visibility ()); + + for (auto &item : extern_block.get_extern_items ()) + { + resolve_extern_item (item.get ()); + } +} + +void +ResolveItem::resolve_impl_item (AST::TraitImplItem *item, + const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix) +{ + ResolveImplItems::go (item, prefix, canonical_prefix); +} + +void +ResolveItem::resolve_impl_item (AST::InherentImplItem *item, + const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix) +{ + ResolveImplItems::go (item, prefix, canonical_prefix); +} + +void +ResolveItem::resolve_extern_item (AST::ExternalItem *item) +{ + ResolveExternItem::go (item, prefix, canonical_prefix); +} + +static void +flatten_glob (const AST::UseTreeGlob &glob, + std::vector &paths); +static void +flatten_rebind (const AST::UseTreeRebind &glob, + std::vector &paths); +static void +flatten_list (const AST::UseTreeList &glob, + std::vector &paths); + +static void +flatten (const AST::UseTree *tree, std::vector &paths) +{ + switch (tree->get_kind ()) + { + case AST::UseTree::Glob: { + auto glob = static_cast (tree); + flatten_glob (*glob, paths); + break; + } + case AST::UseTree::Rebind: { + auto rebind = static_cast (tree); + flatten_rebind (*rebind, paths); + break; + } + case AST::UseTree::List: { + auto list = static_cast (tree); + flatten_list (*list, paths); + break; + } + break; + } +} + +static void +flatten_glob (const AST::UseTreeGlob &glob, std::vector &paths) +{ + if (glob.has_path ()) + paths.emplace_back (glob.get_path ()); +} + +static void +flatten_rebind (const AST::UseTreeRebind &rebind, + std::vector &paths) +{ + auto path = rebind.get_path (); + if (rebind.has_path ()) + paths.emplace_back (path); + + // FIXME: Do we want to emplace the rebind here as well? + if (rebind.has_identifier ()) + { + auto rebind_path = path; + auto new_seg = rebind.get_identifier (); + + // Add the identifier as a new path + rebind_path.get_segments ().back () + = AST::SimplePathSegment (new_seg, Location ()); + + paths.emplace_back (rebind_path); + } +} + +static void +flatten_list (const AST::UseTreeList &list, std::vector &paths) +{ + auto prefix = AST::SimplePath::create_empty (); + if (list.has_path ()) + prefix = list.get_path (); + + for (const auto &tree : list.get_trees ()) + { + auto sub_paths = std::vector (); + flatten (tree.get (), sub_paths); + + for (auto &sub_path : sub_paths) + { + auto new_path = prefix; + std::copy (sub_path.get_segments ().begin (), + sub_path.get_segments ().end (), + std::back_inserter (new_path.get_segments ())); + + paths.emplace_back (new_path); + } + } +} + +/** + * Flatten a UseDeclaration's UseTree into multiple simple paths to resolve. + * + * Given the following use declarations: + * ``` + * use some::path::to_resolve; #1 + * use some::path::to_glob::*; #2 + * use some::path::{one, two}; #2 + * ``` + * + * In the first case, we simply want to return a vector with a single + * SimplePath: + * [some::path::to_resolve] + * + * In the second case, we want to resolve the glob's "origin path": + * [some::path::to_glob] + * + * Finally in the third case, we want to create two SimplePaths to resolve: + * [some::path::one, some::path::two] + */ +static std::vector +flatten_use_dec_to_paths (const AST::UseDeclaration &use_item) +{ + auto paths = std::vector (); + + const auto &tree = use_item.get_tree (); + flatten (tree.get (), paths); + + return paths; +} + +void +ResolveItem::visit (AST::UseDeclaration &use_item) +{ + auto to_resolve = flatten_use_dec_to_paths (use_item); + + for (auto &path : to_resolve) + ResolvePath::go (&path); +} + +ResolveImplItems::ResolveImplItems (const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix) + : ResolveItem (prefix, canonical_prefix) +{} + +void +ResolveImplItems::go (AST::InherentImplItem *item, const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix) +{ + if (item->is_marked_for_strip ()) + return; + + ResolveImplItems resolver (prefix, canonical_prefix); + item->accept_vis (resolver); +} + +void +ResolveImplItems::go (AST::TraitImplItem *item, const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix) +{ + if (item->is_marked_for_strip ()) + return; + + ResolveImplItems resolver (prefix, canonical_prefix); + item->accept_vis (resolver); +} + +void +ResolveImplItems::visit (AST::TypeAlias &alias) +{ + ResolveItem::visit (alias); + + resolve_visibility (alias.get_visibility ()); + + // FIXME this stops the erronious unused decls which will be fixed later on + resolver->get_type_scope ().append_reference_for_def (alias.get_node_id (), + alias.get_node_id ()); +} + +void +ResolveExternItem::go (AST::ExternalItem *item, const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix) +{ + ResolveExternItem resolver (prefix, canonical_prefix); + item->accept_vis (resolver); +} + +void +ResolveExternItem::visit (AST::ExternalFunctionItem &function) +{ + NodeId scope_node_id = function.get_node_id (); + auto decl = CanonicalPath::new_seg (function.get_node_id (), + function.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + + mappings->insert_canonical_path (function.get_node_id (), cpath); + + resolve_visibility (function.get_visibility ()); + + resolver->get_name_scope ().push (scope_node_id); + resolver->get_type_scope ().push (scope_node_id); + resolver->get_label_scope ().push (scope_node_id); + resolver->push_new_name_rib (resolver->get_name_scope ().peek ()); + resolver->push_new_type_rib (resolver->get_type_scope ().peek ()); + resolver->push_new_label_rib (resolver->get_type_scope ().peek ()); + + // resolve the generics + if (function.has_generics ()) + for (auto &generic : function.get_generic_params ()) + ResolveGenericParam::go (generic.get (), prefix, canonical_prefix); + + if (function.has_return_type ()) + ResolveType::go (function.get_return_type ().get ()); + + // we make a new scope so the names of parameters are resolved and shadowed + // correctly + for (auto ¶m : function.get_function_params ()) + { + ResolveType::go (param.get_type ().get ()); + } + + // done + resolver->get_name_scope ().pop (); + resolver->get_type_scope ().pop (); + resolver->get_label_scope ().pop (); +} + +void +ResolveExternItem::visit (AST::ExternalStaticItem &item) +{ + resolve_visibility (item.get_visibility ()); + + ResolveType::go (item.get_type ().get ()); +} + +} // namespace Resolver +} // namespace Rust + +#if CHECKING_P + +namespace selftest { + +static void +rust_flatten_nested_glob (void) +{ + auto foo = Rust::AST::SimplePathSegment ("foo", Location ()); + auto bar = Rust::AST::SimplePathSegment ("bar", Location ()); + auto foobar = Rust::AST::SimplePath ({foo, bar}); + + auto glob + = Rust::AST::UseTreeGlob (Rust::AST::UseTreeGlob::PathType::PATH_PREFIXED, + foobar, Location ()); + + auto paths = std::vector (); + Rust::Resolver::flatten_glob (glob, paths); + + ASSERT_TRUE (!paths.empty ()); + ASSERT_EQ (paths.size (), 1); + ASSERT_EQ (paths[0].get_segments ()[0].as_string (), "foo"); + ASSERT_EQ (paths[0].get_segments ()[1].as_string (), "bar"); +} + +static void +rust_flatten_glob (void) +{ + auto frob = Rust::AST::SimplePath::from_str ("frobulator", Location ()); + + auto glob + = Rust::AST::UseTreeGlob (Rust::AST::UseTreeGlob::PathType::PATH_PREFIXED, + frob, Location ()); + + auto paths = std::vector (); + Rust::Resolver::flatten_glob (glob, paths); + + ASSERT_TRUE (!paths.empty ()); + ASSERT_EQ (paths.size (), 1); + ASSERT_EQ (paths[0], "frobulator"); +} + +static void +rust_flatten_rebind_none (void) +{ + auto foo = Rust::AST::SimplePathSegment ("foo", Location ()); + auto bar = Rust::AST::SimplePathSegment ("bar", Location ()); + auto foobar = Rust::AST::SimplePath ({foo, bar}); + + auto rebind = Rust::AST::UseTreeRebind (Rust::AST::UseTreeRebind::NONE, + foobar, Location ()); + + auto paths = std::vector (); + Rust::Resolver::flatten_rebind (rebind, paths); + + ASSERT_TRUE (!paths.empty ()); + ASSERT_EQ (paths.size (), 1); + ASSERT_EQ (paths[0].get_segments ()[0].as_string (), "foo"); + ASSERT_EQ (paths[0].get_segments ()[1].as_string (), "bar"); +} + +static void +rust_flatten_rebind (void) +{ + auto frob = Rust::AST::SimplePath::from_str ("frobulator", Location ()); + + auto rebind = Rust::AST::UseTreeRebind (Rust::AST::UseTreeRebind::IDENTIFIER, + frob, Location (), "saindoux"); + + auto paths = std::vector (); + Rust::Resolver::flatten_rebind (rebind, paths); + + ASSERT_TRUE (!paths.empty ()); + ASSERT_EQ (paths.size (), 2); + ASSERT_EQ (paths[0], "frobulator"); + ASSERT_EQ (paths[1], "saindoux"); +} + +static void +rust_flatten_rebind_nested (void) +{ + auto foo = Rust::AST::SimplePathSegment ("foo", Location ()); + auto bar = Rust::AST::SimplePathSegment ("bar", Location ()); + auto baz = Rust::AST::SimplePathSegment ("baz", Location ()); + + auto foo_bar_baz = Rust::AST::SimplePath ({foo, bar, baz}); + + auto rebind = Rust::AST::UseTreeRebind (Rust::AST::UseTreeRebind::IDENTIFIER, + foo_bar_baz, Location (), "saindoux"); + + auto paths = std::vector (); + Rust::Resolver::flatten_rebind (rebind, paths); + + ASSERT_TRUE (!paths.empty ()); + ASSERT_EQ (paths.size (), 2); + ASSERT_EQ (paths[0].get_segments ()[0].as_string (), "foo"); + ASSERT_EQ (paths[0].get_segments ()[1].as_string (), "bar"); + ASSERT_EQ (paths[0].get_segments ()[2].as_string (), "baz"); + ASSERT_EQ (paths[1].get_segments ()[0].as_string (), "foo"); + ASSERT_EQ (paths[1].get_segments ()[1].as_string (), "bar"); + ASSERT_EQ (paths[1].get_segments ()[2].as_string (), "saindoux"); +} + +static void +rust_flatten_list (void) +{ + auto foo = Rust::AST::SimplePathSegment ("foo", Location ()); + auto bar = Rust::AST::SimplePathSegment ("bar", Location ()); + auto foo_bar = Rust::AST::SimplePath ({foo, bar}); + + auto baz = Rust::AST::SimplePath::from_str ("baz", Location ()); + auto bul = Rust::AST::SimplePath::from_str ("bul", Location ()); + + // use foo::bar::{baz, bul}; + + auto use0 = std::unique_ptr ( + new Rust::AST::UseTreeRebind (Rust::AST::UseTreeRebind::NONE, baz, + Location ())); + auto use1 = std::unique_ptr ( + new Rust::AST::UseTreeRebind (Rust::AST::UseTreeRebind::NONE, bul, + Location ())); + + auto uses = std::vector> (); + uses.emplace_back (std::move (use0)); + uses.emplace_back (std::move (use1)); + + auto list = Rust::AST::UseTreeList (Rust::AST::UseTreeList::PATH_PREFIXED, + foo_bar, std::move (uses), Location ()); + + auto paths = std::vector (); + Rust::Resolver::flatten_list (list, paths); + + for (auto &path : paths) + fprintf (stderr, "%s\n", path.as_string ().c_str ()); + + ASSERT_TRUE (!paths.empty ()); + ASSERT_EQ (paths.size (), 2); + ASSERT_EQ (paths[0].get_segments ()[0].as_string (), "foo"); + ASSERT_EQ (paths[0].get_segments ()[1].as_string (), "bar"); + ASSERT_EQ (paths[0].get_segments ()[2].as_string (), "baz"); + ASSERT_EQ (paths[1].get_segments ()[0].as_string (), "foo"); + ASSERT_EQ (paths[1].get_segments ()[1].as_string (), "bar"); + ASSERT_EQ (paths[1].get_segments ()[2].as_string (), "bul"); +} + +static void +rust_use_dec_flattening (void) +{ + rust_flatten_glob (); + rust_flatten_nested_glob (); + rust_flatten_rebind_none (); + rust_flatten_rebind (); + rust_flatten_rebind_nested (); + rust_flatten_list (); +} + +void +rust_simple_path_resolve_test (void) +{ + rust_use_dec_flattening (); +} + +} // namespace selftest + +#endif // CHECKING_P diff --git a/gcc/rust/resolve/rust-ast-resolve-item.h b/gcc/rust/resolve/rust-ast-resolve-item.h new file mode 100644 index 00000000000..ce521f057f6 --- /dev/null +++ b/gcc/rust/resolve/rust-ast-resolve-item.h @@ -0,0 +1,149 @@ +// Copyright (C) 2020-2022 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 +// . + +#ifndef RUST_AST_RESOLVE_ITEM_H +#define RUST_AST_RESOLVE_ITEM_H + +#include "rust-ast-full-decls.h" +#include "rust-ast-resolve-base.h" +#include "rust-ast-full.h" +#include "rust-ast-resolve-toplevel.h" +#include "rust-ast-resolve-type.h" +#include "rust-ast-resolve-pattern.h" +#include "rust-ast-resolve-stmt.h" +#include "config.h" + +namespace Rust { +namespace Resolver { + +class ResolveTraitItems : public ResolverBase +{ + using Rust::Resolver::ResolverBase::visit; + +public: + static void go (AST::TraitItem *item, const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix); + + void visit (AST::TraitItemType &type) override; + void visit (AST::TraitItemFunc &func) override; + void visit (AST::TraitItemMethod &func) override; + void visit (AST::TraitItemConst &constant) override; + +private: + ResolveTraitItems (const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix); + + const CanonicalPath &prefix; + const CanonicalPath &canonical_prefix; +}; + +class ResolveItem : public ResolverBase +{ +public: + using Rust::Resolver::ResolverBase::visit; + + static void go (AST::Item *item, const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix); + + void visit (AST::TypeAlias &alias) override; + void visit (AST::Module &module) override; + void visit (AST::TupleStruct &struct_decl) override; + void visit (AST::Enum &enum_decl) override; + /* EnumItem doesn't need to be handled, no fields. */ + void visit (AST::EnumItem &item) override; + void visit (AST::EnumItemTuple &item) override; + void visit (AST::EnumItemStruct &item) override; + void visit (AST::EnumItemDiscriminant &item) override; + void visit (AST::StructStruct &struct_decl) override; + void visit (AST::Union &union_decl) override; + void visit (AST::StaticItem &var) override; + void visit (AST::ConstantItem &constant) override; + void visit (AST::Function &function) override; + void visit (AST::InherentImpl &impl_block) override; + void visit (AST::Method &method) override; + void visit (AST::TraitImpl &impl_block) override; + void visit (AST::Trait &trait) override; + void visit (AST::ExternBlock &extern_block) override; + void visit (AST::UseDeclaration &) override; + +protected: + void resolve_impl_item (AST::TraitImplItem *item, const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix); + void resolve_impl_item (AST::InherentImplItem *item, + const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix); + void resolve_extern_item (AST::ExternalItem *item); + + ResolveItem (const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix); + + const CanonicalPath &prefix; + const CanonicalPath &canonical_prefix; +}; + +class ResolveImplItems : public ResolveItem +{ + using Rust::Resolver::ResolveItem::visit; + +public: + static void go (AST::InherentImplItem *item, const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix); + static void go (AST::TraitImplItem *item, const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix); + + void visit (AST::TypeAlias &alias) override; + +private: + ResolveImplItems (const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix); +}; + +class ResolveExternItem : public ResolverBase +{ + using Rust::Resolver::ResolverBase::visit; + +public: + static void go (AST::ExternalItem *item, const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix); + + void visit (AST::ExternalFunctionItem &function) override; + void visit (AST::ExternalStaticItem &item) override; + +private: + ResolveExternItem (const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix) + : ResolverBase (), prefix (prefix), canonical_prefix (canonical_prefix) + {} + + const CanonicalPath &prefix; + const CanonicalPath &canonical_prefix; +}; + +} // namespace Resolver +} // namespace Rust + +#if CHECKING_P + +namespace selftest { +extern void +rust_simple_path_resolve_test (void); +} // namespace selftest + +#endif // CHECKING_P + +#endif // RUST_AST_RESOLVE_ITEM_H diff --git a/gcc/rust/resolve/rust-ast-resolve-path.cc b/gcc/rust/resolve/rust-ast-resolve-path.cc new file mode 100644 index 00000000000..b139c6a8720 --- /dev/null +++ b/gcc/rust/resolve/rust-ast-resolve-path.cc @@ -0,0 +1,384 @@ +// Copyright (C) 2020-2022 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 +// . + +#include "rust-ast-resolve-path.h" +#include "rust-ast-resolve-type.h" +#include "rust-path.h" + +namespace Rust { +namespace Resolver { + +ResolvePath::ResolvePath () : ResolverBase () {} + +void +ResolvePath::go (AST::PathInExpression *expr) +{ + ResolvePath resolver; + resolver.resolve_path (expr); +} + +void +ResolvePath::go (AST::QualifiedPathInExpression *expr) +{ + ResolvePath resolver; + resolver.resolve_path (expr); +} + +void +ResolvePath::go (AST::SimplePath *expr) +{ + ResolvePath resolver; + resolver.resolve_path (expr); +} + +void +ResolvePath::resolve_path (AST::PathInExpression *expr) +{ + NodeId resolved_node_id = UNKNOWN_NODEID; + NodeId module_scope_id = resolver->peek_current_module_scope (); + NodeId previous_resolved_node_id = module_scope_id; + for (size_t i = 0; i < expr->get_segments ().size (); i++) + { + auto &segment = expr->get_segments ().at (i); + const AST::PathIdentSegment &ident_seg = segment.get_ident_segment (); + bool is_first_segment = i == 0; + resolved_node_id = UNKNOWN_NODEID; + + bool in_middle_of_path = i > 0; + if (in_middle_of_path && segment.is_lower_self_seg ()) + { + // error[E0433]: failed to resolve: `self` in paths can only be used + // in start position + rust_error_at (segment.get_locus (), + "failed to resolve: %<%s%> in paths can only be used " + "in start position", + segment.as_string ().c_str ()); + return; + } + + NodeId crate_scope_id = resolver->peek_crate_module_scope (); + if (segment.is_crate_path_seg ()) + { + // what is the current crate scope node id? + module_scope_id = crate_scope_id; + previous_resolved_node_id = module_scope_id; + resolver->insert_resolved_name (segment.get_node_id (), + module_scope_id); + continue; + } + else if (segment.is_super_path_seg ()) + { + if (module_scope_id == crate_scope_id) + { + rust_error_at (segment.get_locus (), + "cannot use % at the crate scope"); + return; + } + + module_scope_id = resolver->peek_parent_module_scope (); + previous_resolved_node_id = module_scope_id; + resolver->insert_resolved_name (segment.get_node_id (), + module_scope_id); + continue; + } + + // resolve any generic args + if (segment.has_generic_args ()) + ResolveGenericArgs::go (segment.get_generic_args ()); + + // logic is awkward here there are a few cases + // + // T::Default + // mod::foo::impl_item + // super::super::module::item + // self + // self::foo + // self::foo::baz + // + // T::Default we can only resolve the T and cant do anything about Default + // its dependant on associated types + // + // mod::foo::impl_item + // we can resolve mod::foo but nothing about impl_item but we need to + // _always resolve generic arguments + // + // self is a simple single lookup + // + // we have module_scope_id for the next module_scope to lookup + // resolved_node_id is the thing we have resolve this segment to + // + // new algo? + // we can only use module resolution when the previous segment is either + // unknown or equal to this module_scope_id + // + // can only use old resolution when previous segment is unkown + + if (is_first_segment) + { + // name scope first + NodeId resolved_node = UNKNOWN_NODEID; + const CanonicalPath path + = CanonicalPath::new_seg (segment.get_node_id (), + ident_seg.as_string ()); + if (resolver->get_name_scope ().lookup (path, &resolved_node)) + { + resolver->insert_resolved_name (segment.get_node_id (), + resolved_node); + resolved_node_id = resolved_node; + } + // check the type scope + else if (resolver->get_type_scope ().lookup (path, &resolved_node)) + { + resolver->insert_resolved_type (segment.get_node_id (), + resolved_node); + resolved_node_id = resolved_node; + } + else if (segment.is_lower_self_seg ()) + { + module_scope_id = crate_scope_id; + previous_resolved_node_id = module_scope_id; + resolver->insert_resolved_name (segment.get_node_id (), + module_scope_id); + continue; + } + else + { + // no error handling here since we might be able to resolve via + // the module hierarchy and handle errors at the end + } + } + + if (resolved_node_id == UNKNOWN_NODEID + && previous_resolved_node_id == module_scope_id) + { + Optional resolved_child + = mappings->lookup_module_child (module_scope_id, + ident_seg.as_string ()); + if (resolved_child.is_some ()) + { + NodeId resolved_node = resolved_child->get_node_id (); + if (resolver->get_name_scope ().decl_was_declared_here ( + resolved_node)) + { + resolved_node_id = resolved_node; + resolver->insert_resolved_name (segment.get_node_id (), + resolved_node); + } + else if (resolver->get_type_scope ().decl_was_declared_here ( + resolved_node)) + { + resolved_node_id = resolved_node; + resolver->insert_resolved_type (segment.get_node_id (), + resolved_node); + } + else + { + rust_error_at (segment.get_locus (), + "Cannot find path %<%s%> in this scope", + segment.as_string ().c_str ()); + return; + } + } + } + + bool did_resolve_segment = resolved_node_id != UNKNOWN_NODEID; + if (did_resolve_segment) + { + if (mappings->node_is_module (resolved_node_id) + || mappings->node_is_crate (resolved_node_id)) + { + module_scope_id = resolved_node_id; + } + previous_resolved_node_id = resolved_node_id; + } + else if (is_first_segment) + { + rust_error_at (segment.get_locus (), + "Cannot find path %<%s%> in this scope", + segment.as_string ().c_str ()); + return; + } + } + + resolved_node = resolved_node_id; + if (resolved_node_id != UNKNOWN_NODEID) + { + // name scope first + if (resolver->get_name_scope ().decl_was_declared_here (resolved_node_id)) + { + resolver->insert_resolved_name (expr->get_node_id (), + resolved_node_id); + } + // check the type scope + else if (resolver->get_type_scope ().decl_was_declared_here ( + resolved_node_id)) + { + resolver->insert_resolved_type (expr->get_node_id (), + resolved_node_id); + } + else + { + gcc_unreachable (); + } + } +} + +void +ResolvePath::resolve_path (AST::QualifiedPathInExpression *expr) +{ + AST::QualifiedPathType &root_segment = expr->get_qualified_path_type (); + ResolveType::go (root_segment.get_type ().get ()); + if (root_segment.has_as_clause ()) + ResolveType::go (&root_segment.get_as_type_path ()); + + for (auto &segment : expr->get_segments ()) + { + // we cant actually do anything with the segment itself since this is all + // the job of the type system to figure it out but we can resolve any + // generic arguments used + if (segment.has_generic_args ()) + ResolveGenericArgs::go (segment.get_generic_args ()); + } +} + +void +ResolvePath::resolve_path (AST::SimplePath *expr) +{ + NodeId crate_scope_id = resolver->peek_crate_module_scope (); + NodeId module_scope_id = resolver->peek_current_module_scope (); + + NodeId resolved_node_id = UNKNOWN_NODEID; + for (size_t i = 0; i < expr->get_segments ().size (); i++) + { + auto &segment = expr->get_segments ().at (i); + bool is_first_segment = i == 0; + resolved_node_id = UNKNOWN_NODEID; + + if (segment.is_crate_path_seg ()) + { + // what is the current crate scope node id? + module_scope_id = crate_scope_id; + resolver->insert_resolved_name (segment.get_node_id (), + module_scope_id); + continue; + } + else if (segment.is_super_path_seg ()) + { + if (module_scope_id == crate_scope_id) + { + rust_error_at (segment.get_locus (), + "cannot use % at the crate scope"); + return; + } + + module_scope_id = resolver->peek_parent_module_scope (); + resolver->insert_resolved_name (segment.get_node_id (), + module_scope_id); + continue; + } + + Optional resolved_child + = mappings->lookup_module_child (module_scope_id, + segment.get_segment_name ()); + if (resolved_child.is_some ()) + { + NodeId resolved_node = resolved_child->get_node_id (); + if (resolver->get_name_scope ().decl_was_declared_here ( + resolved_node)) + { + resolved_node_id = resolved_node; + resolver->insert_resolved_name (segment.get_node_id (), + resolved_node); + } + else if (resolver->get_type_scope ().decl_was_declared_here ( + resolved_node)) + { + resolved_node_id = resolved_node; + resolver->insert_resolved_type (segment.get_node_id (), + resolved_node); + } + else + { + rust_error_at (segment.get_locus (), + "Cannot find path %<%s%> in this scope", + segment.as_string ().c_str ()); + return; + } + } + + if (resolved_node_id == UNKNOWN_NODEID && is_first_segment) + { + // name scope first + NodeId resolved_node = UNKNOWN_NODEID; + const CanonicalPath path + = CanonicalPath::new_seg (segment.get_node_id (), + segment.get_segment_name ()); + if (resolver->get_name_scope ().lookup (path, &resolved_node)) + { + resolved_node_id = resolved_node; + resolver->insert_resolved_name (segment.get_node_id (), + resolved_node); + } + // check the type scope + else if (resolver->get_type_scope ().lookup (path, &resolved_node)) + { + resolved_node_id = resolved_node; + resolver->insert_resolved_type (segment.get_node_id (), + resolved_node); + } + } + + if (resolved_node_id == UNKNOWN_NODEID) + { + rust_error_at (segment.get_locus (), + "cannot find simple path segment %<%s%> in this scope", + segment.as_string ().c_str ()); + return; + } + + if (mappings->node_is_module (resolved_node_id)) + { + module_scope_id = resolved_node_id; + } + } + + resolved_node = resolved_node_id; + if (resolved_node_id != UNKNOWN_NODEID) + { + // name scope first + if (resolver->get_name_scope ().decl_was_declared_here (resolved_node_id)) + { + resolver->insert_resolved_name (expr->get_node_id (), + resolved_node_id); + } + // check the type scope + else if (resolver->get_type_scope ().decl_was_declared_here ( + resolved_node_id)) + { + resolver->insert_resolved_type (expr->get_node_id (), + resolved_node_id); + } + else + { + gcc_unreachable (); + } + } +} + +} // namespace Resolver +} // namespace Rust diff --git a/gcc/rust/resolve/rust-ast-resolve-path.h b/gcc/rust/resolve/rust-ast-resolve-path.h new file mode 100644 index 00000000000..a9af0c5819c --- /dev/null +++ b/gcc/rust/resolve/rust-ast-resolve-path.h @@ -0,0 +1,52 @@ +// Copyright (C) 2020-2022 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 +// . + +#ifndef RUST_AST_RESOLVE_PATH_H +#define RUST_AST_RESOLVE_PATH_H + +#include "rust-ast-resolve-base.h" + +namespace Rust { +namespace Resolver { + +class ResolvePath : public ResolverBase +{ + using Rust::Resolver::ResolverBase::visit; + +public: + static void go (AST::PathInExpression *expr); + static void go (AST::QualifiedPathInExpression *expr); + static void go (AST::SimplePath *expr); + +private: + ResolvePath (); + + void resolve_path (AST::PathInExpression *expr); + void resolve_path (AST::QualifiedPathInExpression *expr); + void resolve_path (AST::SimplePath *expr); + + void + resolve_simple_path_segments (CanonicalPath prefix, size_t offs, + const std::vector &segs, + NodeId expr_node_id, Location expr_locus); +}; + +} // namespace Resolver +} // namespace Rust + +#endif // !RUST_AST_RESOLVE_PATH_H diff --git a/gcc/rust/resolve/rust-ast-resolve-pattern.cc b/gcc/rust/resolve/rust-ast-resolve-pattern.cc new file mode 100644 index 00000000000..9386d36d25e --- /dev/null +++ b/gcc/rust/resolve/rust-ast-resolve-pattern.cc @@ -0,0 +1,163 @@ +// Copyright (C) 2020-2022 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 +// . + +#include "rust-ast-resolve-pattern.h" +#include "rust-ast-resolve-path.h" +#include "rust-ast-resolve-expr.h" + +namespace Rust { +namespace Resolver { + +void +PatternDeclaration::visit (AST::PathInExpression &pattern) +{ + ResolvePath::go (&pattern); +} + +void +PatternDeclaration::visit (AST::TupleStructPattern &pattern) +{ + ResolvePath::go (&pattern.get_path ()); + + std::unique_ptr &items = pattern.get_items (); + switch (items->get_item_type ()) + { + case AST::TupleStructItems::RANGE: { + // TODO + gcc_unreachable (); + } + break; + + case AST::TupleStructItems::NO_RANGE: { + AST::TupleStructItemsNoRange &items_no_range + = static_cast (*items.get ()); + + for (auto &inner_pattern : items_no_range.get_patterns ()) + { + PatternDeclaration::go (inner_pattern.get ()); + } + } + break; + } +} + +void +PatternDeclaration::visit (AST::StructPattern &pattern) +{ + ResolvePath::go (&pattern.get_path ()); + + auto &struct_pattern_elems = pattern.get_struct_pattern_elems (); + for (auto &field : struct_pattern_elems.get_struct_pattern_fields ()) + { + switch (field->get_item_type ()) + { + case AST::StructPatternField::ItemType::TUPLE_PAT: { + // TODO + gcc_unreachable (); + } + break; + + case AST::StructPatternField::ItemType::IDENT_PAT: { + // TODO + gcc_unreachable (); + } + break; + + case AST::StructPatternField::ItemType::IDENT: { + AST::StructPatternFieldIdent &ident + = static_cast (*field.get ()); + + resolver->get_name_scope ().insert ( + CanonicalPath::new_seg (ident.get_node_id (), + ident.get_identifier ()), + ident.get_node_id (), ident.get_locus ()); + } + break; + } + } + + // TODO + rust_assert (!struct_pattern_elems.has_etc ()); +} + +void +PatternDeclaration::visit (AST::TuplePattern &pattern) +{ + std::unique_ptr &items = pattern.get_items (); + switch (items->get_pattern_type ()) + { + case AST::TuplePatternItems::TuplePatternItemType::MULTIPLE: { + AST::TuplePatternItemsMultiple &ref + = *static_cast ( + pattern.get_items ().get ()); + + for (auto &p : ref.get_patterns ()) + p->accept_vis (*this); + } + break; + + case AST::TuplePatternItems::TuplePatternItemType::RANGED: { + AST::TuplePatternItemsRanged &ref + = *static_cast ( + pattern.get_items ().get ()); + + for (auto &p : ref.get_lower_patterns ()) + p->accept_vis (*this); + for (auto &p : ref.get_upper_patterns ()) + p->accept_vis (*this); + } + break; + } +} + +static void +resolve_range_pattern_bound (AST::RangePatternBound *bound) +{ + switch (bound->get_bound_type ()) + { + case AST::RangePatternBound::RangePatternBoundType::LITERAL: + // Nothing to resolve for a literal. + break; + + case AST::RangePatternBound::RangePatternBoundType::PATH: { + AST::RangePatternBoundPath &ref + = *static_cast (bound); + + ResolvePath::go (&ref.get_path ()); + } + break; + + case AST::RangePatternBound::RangePatternBoundType::QUALPATH: { + AST::RangePatternBoundQualPath &ref + = *static_cast (bound); + + ResolvePath::go (&ref.get_qualified_path ()); + } + break; + } +} + +void +PatternDeclaration::visit (AST::RangePattern &pattern) +{ + resolve_range_pattern_bound (pattern.get_upper_bound ().get ()); + resolve_range_pattern_bound (pattern.get_lower_bound ().get ()); +} + +} // namespace Resolver +} // namespace Rust diff --git a/gcc/rust/resolve/rust-ast-resolve-pattern.h b/gcc/rust/resolve/rust-ast-resolve-pattern.h new file mode 100644 index 00000000000..fcbb23fdf08 --- /dev/null +++ b/gcc/rust/resolve/rust-ast-resolve-pattern.h @@ -0,0 +1,98 @@ +// Copyright (C) 2020-2022 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 +// . + +#ifndef RUST_AST_RESOLVE_PATTERN_H +#define RUST_AST_RESOLVE_PATTERN_H + +#include "rust-ast-resolve-base.h" +#include "rust-ast-full.h" + +namespace Rust { +namespace Resolver { + +class ResolvePattern : public ResolverBase +{ + using Rust::Resolver::ResolverBase::visit; + +public: + static void go (AST::Pattern *pattern) + { + ResolvePattern resolver; + pattern->accept_vis (resolver); + } + + void visit (AST::IdentifierPattern &pattern) override + { + if (resolver->get_name_scope ().lookup ( + CanonicalPath::new_seg (pattern.get_node_id (), pattern.get_ident ()), + &resolved_node)) + { + resolver->insert_resolved_name (pattern.get_node_id (), resolved_node); + } + } + +private: + ResolvePattern () : ResolverBase () {} +}; + +class PatternDeclaration : public ResolverBase +{ + using Rust::Resolver::ResolverBase::visit; + +public: + static void go (AST::Pattern *pattern) + { + PatternDeclaration resolver; + pattern->accept_vis (resolver); + }; + + void visit (AST::IdentifierPattern &pattern) override + { + // if we have a duplicate id this then allows for shadowing correctly + // as new refs to this decl will match back here so it is ok to overwrite + resolver->get_name_scope ().insert ( + CanonicalPath::new_seg (pattern.get_node_id (), pattern.get_ident ()), + pattern.get_node_id (), pattern.get_locus ()); + } + + void visit (AST::WildcardPattern &pattern) override + { + resolver->get_name_scope ().insert ( + CanonicalPath::new_seg (pattern.get_node_id (), "_"), + pattern.get_node_id (), pattern.get_locus ()); + } + + // cases in a match expression + void visit (AST::PathInExpression &pattern) override; + + void visit (AST::StructPattern &pattern) override; + + void visit (AST::TupleStructPattern &pattern) override; + + void visit (AST::TuplePattern &pattern) override; + + void visit (AST::RangePattern &pattern) override; + +private: + PatternDeclaration () : ResolverBase () {} +}; + +} // namespace Resolver +} // namespace Rust + +#endif // RUST_AST_RESOLVE_PATTERN_H diff --git a/gcc/rust/resolve/rust-ast-resolve-stmt.cc b/gcc/rust/resolve/rust-ast-resolve-stmt.cc new file mode 100644 index 00000000000..1ce3df0891c --- /dev/null +++ b/gcc/rust/resolve/rust-ast-resolve-stmt.cc @@ -0,0 +1,38 @@ +// Copyright (C) 2020-2022 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 +// . + +#include "rust-ast-resolve-item.h" +#include "rust-ast-resolve-stmt.h" + +namespace Rust { +namespace Resolver { + +void +ResolveStmt::visit (AST::ExternBlock &extern_block) +{ + resolve_visibility (extern_block.get_visibility ()); + for (auto &item : extern_block.get_extern_items ()) + { + ResolveToplevelExternItem::go (item.get (), + CanonicalPath::create_empty ()); + ResolveExternItem::go (item.get (), prefix, canonical_prefix); + } +} + +} // namespace Resolver +} // namespace Rust diff --git a/gcc/rust/resolve/rust-ast-resolve-stmt.h b/gcc/rust/resolve/rust-ast-resolve-stmt.h new file mode 100644 index 00000000000..6f21bc35a33 --- /dev/null +++ b/gcc/rust/resolve/rust-ast-resolve-stmt.h @@ -0,0 +1,378 @@ +// Copyright (C) 2020-2022 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 +// . + +#ifndef RUST_AST_RESOLVE_STMT_H +#define RUST_AST_RESOLVE_STMT_H + +#include "rust-ast-resolve-base.h" +#include "rust-ast-full.h" +#include "rust-ast-resolve-type.h" +#include "rust-ast-resolve-pattern.h" +#include "rust-ast-resolve-expr.h" + +namespace Rust { +namespace Resolver { + +class ResolveStmt : public ResolverBase +{ + using Rust::Resolver::ResolverBase::visit; + +public: + static void go (AST::Stmt *stmt, const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix, + const CanonicalPath &enum_prefix) + { + if (stmt->is_marked_for_strip ()) + return; + + ResolveStmt resolver (prefix, canonical_prefix, enum_prefix); + stmt->accept_vis (resolver); + } + + void visit (AST::ExprStmtWithBlock &stmt) override + { + ResolveExpr::go (stmt.get_expr ().get (), prefix, canonical_prefix); + } + + void visit (AST::ExprStmtWithoutBlock &stmt) override + { + ResolveExpr::go (stmt.get_expr ().get (), prefix, canonical_prefix); + } + + void visit (AST::ConstantItem &constant) override + { + auto decl = CanonicalPath::new_seg (constant.get_node_id (), + constant.get_identifier ()); + auto path = decl; // this ensures we have the correct relative resolution + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (constant.get_node_id (), cpath); + + resolver->get_name_scope ().insert ( + path, constant.get_node_id (), constant.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (constant.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + ResolveType::go (constant.get_type ().get ()); + ResolveExpr::go (constant.get_expr ().get (), prefix, canonical_prefix); + } + + void visit (AST::LetStmt &stmt) override + { + if (stmt.has_init_expr ()) + { + ResolveExpr::go (stmt.get_init_expr ().get (), prefix, + canonical_prefix); + } + + PatternDeclaration::go (stmt.get_pattern ().get ()); + if (stmt.has_type ()) + ResolveType::go (stmt.get_type ().get ()); + } + + void visit (AST::TupleStruct &struct_decl) override + { + auto decl = CanonicalPath::new_seg (struct_decl.get_node_id (), + struct_decl.get_identifier ()); + auto path = decl; // this ensures we have the correct relative resolution + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (struct_decl.get_node_id (), cpath); + + resolver->get_type_scope ().insert ( + path, struct_decl.get_node_id (), struct_decl.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (struct_decl.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + NodeId scope_node_id = struct_decl.get_node_id (); + resolver->get_type_scope ().push (scope_node_id); + + if (struct_decl.has_generics ()) + { + for (auto &generic : struct_decl.get_generic_params ()) + ResolveGenericParam::go (generic.get (), prefix, canonical_prefix); + } + + for (AST::TupleField &field : struct_decl.get_fields ()) + ResolveType::go (field.get_field_type ().get ()); + + resolver->get_type_scope ().pop (); + } + + void visit (AST::Enum &enum_decl) override + { + auto decl = CanonicalPath::new_seg (enum_decl.get_node_id (), + enum_decl.get_identifier ()); + auto path = decl; // this ensures we have the correct relative resolution + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (enum_decl.get_node_id (), cpath); + + resolver->get_type_scope ().insert ( + path, enum_decl.get_node_id (), enum_decl.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (enum_decl.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + NodeId scope_node_id = enum_decl.get_node_id (); + resolver->get_type_scope ().push (scope_node_id); + + if (enum_decl.has_generics ()) + { + for (auto &generic : enum_decl.get_generic_params ()) + ResolveGenericParam::go (generic.get (), prefix, canonical_prefix); + } + + for (auto &variant : enum_decl.get_variants ()) + ResolveStmt::go (variant.get (), path, canonical_prefix, path); + + resolver->get_type_scope ().pop (); + } + + void visit (AST::EnumItem &item) override + { + auto decl = enum_prefix.append ( + CanonicalPath::new_seg (item.get_node_id (), item.get_identifier ())); + auto path = decl; // this ensures we have the correct relative resolution + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (item.get_node_id (), cpath); + + resolver->get_type_scope ().insert ( + path, item.get_node_id (), item.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (item.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + // Done, no fields. + } + + void visit (AST::EnumItemTuple &item) override + { + auto decl = enum_prefix.append ( + CanonicalPath::new_seg (item.get_node_id (), item.get_identifier ())); + auto path = decl; // this ensures we have the correct relative resolution + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (item.get_node_id (), cpath); + + resolver->get_type_scope ().insert ( + path, item.get_node_id (), item.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (item.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + for (auto &field : item.get_tuple_fields ()) + { + if (field.get_field_type ()->is_marked_for_strip ()) + continue; + + ResolveType::go (field.get_field_type ().get ()); + } + } + + void visit (AST::EnumItemStruct &item) override + { + auto decl = enum_prefix.append ( + CanonicalPath::new_seg (item.get_node_id (), item.get_identifier ())); + auto path = decl; // this ensures we have the correct relative resolution + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (item.get_node_id (), cpath); + + resolver->get_type_scope ().insert ( + path, item.get_node_id (), item.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (item.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + for (auto &field : item.get_struct_fields ()) + { + if (field.get_field_type ()->is_marked_for_strip ()) + continue; + + ResolveType::go (field.get_field_type ().get ()); + } + } + + void visit (AST::EnumItemDiscriminant &item) override + { + auto decl = enum_prefix.append ( + CanonicalPath::new_seg (item.get_node_id (), item.get_identifier ())); + auto path = decl; // this ensures we have the correct relative resolution + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (item.get_node_id (), cpath); + + resolver->get_type_scope ().insert ( + path, item.get_node_id (), item.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (item.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + // Done, no fields. + } + + void visit (AST::StructStruct &struct_decl) override + { + auto decl = CanonicalPath::new_seg (struct_decl.get_node_id (), + struct_decl.get_identifier ()); + auto path = decl; // this ensures we have the correct relative resolution + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (struct_decl.get_node_id (), cpath); + + resolver->get_type_scope ().insert ( + path, struct_decl.get_node_id (), struct_decl.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (struct_decl.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + NodeId scope_node_id = struct_decl.get_node_id (); + resolver->get_type_scope ().push (scope_node_id); + + if (struct_decl.has_generics ()) + { + for (auto &generic : struct_decl.get_generic_params ()) + ResolveGenericParam::go (generic.get (), prefix, canonical_prefix); + } + + for (AST::StructField &field : struct_decl.get_fields ()) + { + if (field.get_field_type ()->is_marked_for_strip ()) + continue; + + ResolveType::go (field.get_field_type ().get ()); + } + + resolver->get_type_scope ().pop (); + } + + void visit (AST::Union &union_decl) override + { + auto decl = CanonicalPath::new_seg (union_decl.get_node_id (), + union_decl.get_identifier ()); + auto path = decl; // this ensures we have the correct relative resolution + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (union_decl.get_node_id (), cpath); + + resolver->get_type_scope ().insert ( + path, union_decl.get_node_id (), union_decl.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (union_decl.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + NodeId scope_node_id = union_decl.get_node_id (); + resolver->get_type_scope ().push (scope_node_id); + + if (union_decl.has_generics ()) + for (auto &generic : union_decl.get_generic_params ()) + ResolveGenericParam::go (generic.get (), prefix, canonical_prefix); + + for (AST::StructField &field : union_decl.get_variants ()) + { + if (field.get_field_type ()->is_marked_for_strip ()) + continue; + + ResolveType::go (field.get_field_type ().get ()); + } + + resolver->get_type_scope ().pop (); + } + + void visit (AST::Function &function) override + { + auto decl = CanonicalPath::new_seg (function.get_node_id (), + function.get_function_name ()); + auto path = decl; // this ensures we have the correct relative resolution + auto cpath = canonical_prefix.append (decl); + mappings->insert_canonical_path (function.get_node_id (), cpath); + + resolver->get_name_scope ().insert ( + path, function.get_node_id (), function.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (function.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + NodeId scope_node_id = function.get_node_id (); + resolver->get_name_scope ().push (scope_node_id); + resolver->get_type_scope ().push (scope_node_id); + resolver->get_label_scope ().push (scope_node_id); + resolver->push_new_name_rib (resolver->get_name_scope ().peek ()); + resolver->push_new_type_rib (resolver->get_type_scope ().peek ()); + resolver->push_new_label_rib (resolver->get_type_scope ().peek ()); + + if (function.has_generics ()) + for (auto &generic : function.get_generic_params ()) + ResolveGenericParam::go (generic.get (), prefix, canonical_prefix); + + if (function.has_return_type ()) + ResolveType::go (function.get_return_type ().get ()); + + // we make a new scope so the names of parameters are resolved and shadowed + // correctly + for (auto ¶m : function.get_function_params ()) + { + ResolveType::go (param.get_type ().get ()); + PatternDeclaration::go (param.get_pattern ().get ()); + } + + // resolve the function body + ResolveExpr::go (function.get_definition ().get (), path, cpath); + + resolver->get_name_scope ().pop (); + resolver->get_type_scope ().pop (); + resolver->get_label_scope ().pop (); + } + + void visit (AST::ExternBlock &extern_block) override; + +private: + ResolveStmt (const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix, + const CanonicalPath &enum_prefix) + : ResolverBase (), prefix (prefix), canonical_prefix (canonical_prefix), + enum_prefix (enum_prefix) + {} + + const CanonicalPath &prefix; + const CanonicalPath &canonical_prefix; + + /* item declaration statements are not given a canonical path, but enum items + * (variants) do inherit the enum path/identifier name. */ + const CanonicalPath &enum_prefix; +}; + +} // namespace Resolver +} // namespace Rust + +#endif // RUST_AST_RESOLVE_STMT_H diff --git a/gcc/rust/resolve/rust-ast-resolve-struct-expr-field.cc b/gcc/rust/resolve/rust-ast-resolve-struct-expr-field.cc new file mode 100644 index 00000000000..4d8b6c788f3 --- /dev/null +++ b/gcc/rust/resolve/rust-ast-resolve-struct-expr-field.cc @@ -0,0 +1,61 @@ +// Copyright (C) 2020-2022 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 +// . + +#include "rust-ast-resolve-struct-expr-field.h" +#include "rust-ast-resolve-expr.h" + +namespace Rust { +namespace Resolver { + +void +ResolveStructExprField::go (AST::StructExprField *field, + const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix) +{ + ResolveStructExprField resolver (prefix, canonical_prefix); + field->accept_vis (resolver); +} + +ResolveStructExprField::ResolveStructExprField ( + const CanonicalPath &prefix, const CanonicalPath &canonical_prefix) + : ResolverBase (), prefix (prefix), canonical_prefix (canonical_prefix) +{} + +void +ResolveStructExprField::visit (AST::StructExprFieldIdentifierValue &field) +{ + ResolveExpr::go (field.get_value ().get (), prefix, canonical_prefix); +} + +void +ResolveStructExprField::visit (AST::StructExprFieldIndexValue &field) +{ + ResolveExpr::go (field.get_value ().get (), prefix, canonical_prefix); +} + +void +ResolveStructExprField::visit (AST::StructExprFieldIdentifier &field) +{ + AST::IdentifierExpr expr (field.get_field_name (), {}, field.get_locus ()); + expr.set_node_id (field.get_node_id ()); + + ResolveExpr::go (&expr, prefix, canonical_prefix); +} + +} // namespace Resolver +} // namespace Rust diff --git a/gcc/rust/resolve/rust-ast-resolve-struct-expr-field.h b/gcc/rust/resolve/rust-ast-resolve-struct-expr-field.h new file mode 100644 index 00000000000..ce60b136e4b --- /dev/null +++ b/gcc/rust/resolve/rust-ast-resolve-struct-expr-field.h @@ -0,0 +1,55 @@ +// Copyright (C) 2020-2022 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 +// . + +#ifndef RUST_AST_RESOLVE_STRUCT_EXPR_FIELD +#define RUST_AST_RESOLVE_STRUCT_EXPR_FIELD + +#include "rust-ast-resolve-base.h" +#include "rust-ast-full.h" + +namespace Rust { +namespace Resolver { + +// this resolves values being assigned not that the field actually exists yet. + +class ResolveStructExprField : public ResolverBase +{ + using Rust::Resolver::ResolverBase::visit; + +public: + static void go (AST::StructExprField *field, const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix); + + void visit (AST::StructExprFieldIdentifierValue &field) override; + + void visit (AST::StructExprFieldIndexValue &field) override; + + void visit (AST::StructExprFieldIdentifier &field) override; + +private: + ResolveStructExprField (const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix); + + const CanonicalPath &prefix; + const CanonicalPath &canonical_prefix; +}; + +} // namespace Resolver +} // namespace Rust + +#endif // RUST_AST_RESOLVE_STRUCT_EXPR_FIELD diff --git a/gcc/rust/resolve/rust-ast-resolve-toplevel.h b/gcc/rust/resolve/rust-ast-resolve-toplevel.h new file mode 100644 index 00000000000..43ae8e47673 --- /dev/null +++ b/gcc/rust/resolve/rust-ast-resolve-toplevel.h @@ -0,0 +1,460 @@ +// Copyright (C) 2020-2022 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 +// . + +#ifndef RUST_AST_RESOLVE_TOPLEVEL_H +#define RUST_AST_RESOLVE_TOPLEVEL_H + +#include "rust-ast-resolve-base.h" +#include "rust-ast-resolve-type.h" +#include "rust-ast-resolve-implitem.h" +#include "rust-ast-full.h" +#include "rust-name-resolver.h" +#include "rust-session-manager.h" + +namespace Rust { +namespace Resolver { + +class ResolveTopLevel : public ResolverBase +{ + using Rust::Resolver::ResolverBase::visit; + +public: + static void go (AST::Item *item, const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix) + { + if (item->is_marked_for_strip ()) + return; + + ResolveTopLevel resolver (prefix, canonical_prefix); + item->accept_vis (resolver); + + NodeId current_module = resolver.resolver->peek_current_module_scope (); + resolver.mappings->insert_child_item_to_parent_module_mapping ( + item->get_node_id (), current_module); + } + + void visit (AST::Module &module) override + { + auto mod + = CanonicalPath::new_seg (module.get_node_id (), module.get_name ()); + auto path = prefix.append (mod); + auto cpath = canonical_prefix.append (mod); + + resolver->get_name_scope ().insert ( + path, module.get_node_id (), module.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (module.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + NodeId current_module = resolver->peek_current_module_scope (); + mappings->insert_module_child_item (current_module, mod); + mappings->insert_module_child (current_module, module.get_node_id ()); + + resolver->push_new_module_scope (module.get_node_id ()); + for (auto &item : module.get_items ()) + ResolveTopLevel::go (item.get (), path, cpath); + + resolver->pop_module_scope (); + + mappings->insert_canonical_path (module.get_node_id (), cpath); + } + + void visit (AST::TypeAlias &alias) override + { + auto talias = CanonicalPath::new_seg (alias.get_node_id (), + alias.get_new_type_name ()); + auto path = prefix.append (talias); + auto cpath = canonical_prefix.append (talias); + + resolver->get_type_scope ().insert ( + path, alias.get_node_id (), alias.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (alias.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + NodeId current_module = resolver->peek_current_module_scope (); + mappings->insert_module_child_item (current_module, talias); + mappings->insert_canonical_path (alias.get_node_id (), cpath); + } + + void visit (AST::TupleStruct &struct_decl) override + { + auto decl = CanonicalPath::new_seg (struct_decl.get_node_id (), + struct_decl.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + + resolver->get_type_scope ().insert ( + path, struct_decl.get_node_id (), struct_decl.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (struct_decl.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + NodeId current_module = resolver->peek_current_module_scope (); + mappings->insert_module_child_item (current_module, decl); + mappings->insert_canonical_path (struct_decl.get_node_id (), cpath); + } + + void visit (AST::Enum &enum_decl) override + { + auto decl = CanonicalPath::new_seg (enum_decl.get_node_id (), + enum_decl.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + + resolver->get_type_scope ().insert ( + path, enum_decl.get_node_id (), enum_decl.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (enum_decl.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + for (auto &variant : enum_decl.get_variants ()) + ResolveTopLevel::go (variant.get (), path, cpath); + + NodeId current_module = resolver->peek_current_module_scope (); + mappings->insert_module_child_item (current_module, decl); + mappings->insert_canonical_path (enum_decl.get_node_id (), cpath); + } + + void visit (AST::EnumItem &item) override + { + auto decl + = CanonicalPath::new_seg (item.get_node_id (), item.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + + resolver->get_type_scope ().insert ( + path, item.get_node_id (), item.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (item.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + mappings->insert_canonical_path (item.get_node_id (), cpath); + } + + void visit (AST::EnumItemTuple &item) override + { + auto decl + = CanonicalPath::new_seg (item.get_node_id (), item.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + + resolver->get_type_scope ().insert ( + path, item.get_node_id (), item.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (item.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + mappings->insert_canonical_path (item.get_node_id (), cpath); + } + + void visit (AST::EnumItemStruct &item) override + { + auto decl + = CanonicalPath::new_seg (item.get_node_id (), item.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + + resolver->get_type_scope ().insert ( + path, item.get_node_id (), item.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (item.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + mappings->insert_canonical_path (item.get_node_id (), cpath); + } + + void visit (AST::EnumItemDiscriminant &item) override + { + auto decl + = CanonicalPath::new_seg (item.get_node_id (), item.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + + resolver->get_type_scope ().insert ( + path, item.get_node_id (), item.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (item.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + mappings->insert_canonical_path (item.get_node_id (), cpath); + } + + void visit (AST::StructStruct &struct_decl) override + { + auto decl = CanonicalPath::new_seg (struct_decl.get_node_id (), + struct_decl.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + + resolver->get_type_scope ().insert ( + path, struct_decl.get_node_id (), struct_decl.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (struct_decl.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + NodeId current_module = resolver->peek_current_module_scope (); + mappings->insert_module_child_item (current_module, decl); + mappings->insert_canonical_path (struct_decl.get_node_id (), cpath); + } + + void visit (AST::Union &union_decl) override + { + auto decl = CanonicalPath::new_seg (union_decl.get_node_id (), + union_decl.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + + resolver->get_type_scope ().insert ( + path, union_decl.get_node_id (), union_decl.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (union_decl.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + NodeId current_module = resolver->peek_current_module_scope (); + mappings->insert_module_child_item (current_module, decl); + mappings->insert_canonical_path (union_decl.get_node_id (), cpath); + } + + void visit (AST::StaticItem &var) override + { + auto decl + = CanonicalPath::new_seg (var.get_node_id (), var.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + + resolver->get_name_scope ().insert ( + path, var.get_node_id (), var.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (var.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + NodeId current_module = resolver->peek_current_module_scope (); + mappings->insert_module_child_item (current_module, decl); + mappings->insert_canonical_path (var.get_node_id (), cpath); + } + + void visit (AST::ConstantItem &constant) override + { + auto decl = CanonicalPath::new_seg (constant.get_node_id (), + constant.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + + resolver->get_name_scope ().insert ( + path, constant.get_node_id (), constant.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (constant.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + NodeId current_module = resolver->peek_current_module_scope (); + mappings->insert_module_child_item (current_module, decl); + mappings->insert_canonical_path (constant.get_node_id (), cpath); + } + + void visit (AST::Function &function) override + { + auto decl = CanonicalPath::new_seg (function.get_node_id (), + function.get_function_name ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + + resolver->get_name_scope ().insert ( + path, function.get_node_id (), function.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (function.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + NodeId current_module = resolver->peek_current_module_scope (); + mappings->insert_module_child_item (current_module, decl); + mappings->insert_canonical_path (function.get_node_id (), cpath); + } + + void visit (AST::InherentImpl &impl_block) override + { + std::string raw_impl_type_path = impl_block.get_type ()->as_string (); + CanonicalPath impl_type + = CanonicalPath::new_seg (impl_block.get_type ()->get_node_id (), + raw_impl_type_path); + CanonicalPath impl_prefix = prefix.append (impl_type); + + for (auto &impl_item : impl_block.get_impl_items ()) + ResolveToplevelImplItem::go (impl_item.get (), impl_prefix); + } + + void visit (AST::TraitImpl &impl_block) override + { + std::string raw_impl_type_path = impl_block.get_type ()->as_string (); + CanonicalPath impl_type_seg + = CanonicalPath::new_seg (impl_block.get_type ()->get_node_id (), + raw_impl_type_path); + + std::string raw_trait_type_path = impl_block.get_trait_path ().as_string (); + CanonicalPath trait_type_seg + = CanonicalPath::new_seg (impl_block.get_trait_path ().get_node_id (), + raw_trait_type_path); + + CanonicalPath projection + = CanonicalPath::trait_impl_projection_seg (impl_block.get_node_id (), + trait_type_seg, + impl_type_seg); + CanonicalPath impl_prefix = prefix.append (projection); + + resolver->get_name_scope ().insert ( + impl_prefix, impl_block.get_node_id (), impl_block.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (impl_block.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + for (auto &impl_item : impl_block.get_impl_items ()) + ResolveToplevelImplItem::go (impl_item.get (), impl_prefix); + } + + void visit (AST::Trait &trait) override + { + auto decl + = CanonicalPath::new_seg (trait.get_node_id (), trait.get_identifier ()); + auto path = prefix.append (decl); + auto cpath = canonical_prefix.append (decl); + + resolver->get_type_scope ().insert ( + path, trait.get_node_id (), trait.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (trait.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + + for (auto &item : trait.get_trait_items ()) + ResolveTopLevelTraitItems::go (item.get (), path, cpath); + + NodeId current_module = resolver->peek_current_module_scope (); + mappings->insert_module_child_item (current_module, decl); + mappings->insert_canonical_path (trait.get_node_id (), cpath); + } + + void visit (AST::ExternBlock &extern_block) override + { + for (auto &item : extern_block.get_extern_items ()) + { + ResolveToplevelExternItem::go (item.get (), prefix); + } + } + + void visit (AST::ExternCrate &extern_crate) override + { + if (extern_crate.is_marked_for_strip ()) + return; + + NodeId resolved_crate = UNKNOWN_NODEID; + if (extern_crate.references_self ()) + { + CrateNum crate_num = mappings->get_current_crate (); + bool ok = mappings->crate_num_to_nodeid (crate_num, resolved_crate); + rust_assert (ok); + } + else + { + CrateNum found_crate_num = UNKNOWN_CREATENUM; + bool found + = mappings->lookup_crate_name (extern_crate.get_referenced_crate (), + found_crate_num); + if (!found) + { + rust_error_at (extern_crate.get_locus (), "unknown crate %<%s%>", + extern_crate.get_referenced_crate ().c_str ()); + return; + } + + bool ok + = mappings->crate_num_to_nodeid (found_crate_num, resolved_crate); + if (!ok) + { + rust_internal_error_at (extern_crate.get_locus (), + "failed to resolve crate to nodeid"); + return; + } + } + + if (resolved_crate == UNKNOWN_NODEID) + { + rust_error_at (extern_crate.get_locus (), "failed to resolve crate"); + return; + } + + // mark the node as resolved + resolver->insert_resolved_name (extern_crate.get_node_id (), + resolved_crate); + CanonicalPath decl + = extern_crate.has_as_clause () + ? CanonicalPath::new_seg (extern_crate.get_node_id (), + extern_crate.get_as_clause ()) + : CanonicalPath::new_seg (extern_crate.get_node_id (), + extern_crate.get_referenced_crate ()); + + resolver->get_type_scope ().insert ( + decl, resolved_crate, extern_crate.get_locus (), false, + [&] (const CanonicalPath &, NodeId, Location locus) -> void { + RichLocation r (extern_crate.get_locus ()); + r.add_range (locus); + rust_error_at (r, "redefined multiple times"); + }); + } + +private: + ResolveTopLevel (const CanonicalPath &prefix, + const CanonicalPath &canonical_prefix) + : ResolverBase (), prefix (prefix), canonical_prefix (canonical_prefix) + {} + + const CanonicalPath &prefix; + const CanonicalPath &canonical_prefix; +}; + +} // namespace Resolver +} // namespace Rust + +#endif // RUST_AST_RESOLVE_TOPLEVEL_H diff --git a/gcc/rust/resolve/rust-ast-resolve-type.cc b/gcc/rust/resolve/rust-ast-resolve-type.cc new file mode 100644 index 00000000000..6b08613755a --- /dev/null +++ b/gcc/rust/resolve/rust-ast-resolve-type.cc @@ -0,0 +1,582 @@ +// Copyright (C) 2020-2022 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 +// . + +#include "rust-ast-resolve-type.h" +#include "rust-ast-resolve-expr.h" + +namespace Rust { +namespace Resolver { + +// rust-ast-resolve-type.h + +void +ResolveType::visit (AST::ArrayType &type) +{ + type.get_elem_type ()->accept_vis (*this); + ResolveExpr::go (type.get_size_expr ().get (), CanonicalPath::create_empty (), + CanonicalPath::create_empty ()); +} + +void +ResolveType::visit (AST::TraitObjectTypeOneBound &type) +{ + ResolveTypeBound::go (&type.get_trait_bound ()); +} + +void +ResolveType::visit (AST::TraitObjectType &type) +{ + for (auto &bound : type.get_type_param_bounds ()) + { + /* NodeId bound_resolved_id = */ + ResolveTypeBound::go (bound.get ()); + } +} + +void +ResolveType::visit (AST::ReferenceType &type) +{ + resolved_node = ResolveType::go (type.get_type_referenced ().get ()); +} + +void +ResolveType::visit (AST::RawPointerType &type) +{ + resolved_node = ResolveType::go (type.get_type_pointed_to ().get ()); +} + +void +ResolveType::visit (AST::InferredType &type) +{ + // FIXME +} + +void +ResolveType::visit (AST::NeverType &type) +{ + // FIXME +} + +void +ResolveType::visit (AST::SliceType &type) +{ + resolved_node = ResolveType::go (type.get_elem_type ().get ()); +} + +// resolve relative type-paths + +bool +ResolveRelativeTypePath::go (AST::TypePath &path, NodeId &resolved_node_id) +{ + auto resolver = Resolver::get (); + auto mappings = Analysis::Mappings::get (); + + NodeId module_scope_id = resolver->peek_current_module_scope (); + NodeId previous_resolved_node_id = module_scope_id; + for (size_t i = 0; i < path.get_segments ().size (); i++) + { + auto &segment = path.get_segments ().at (i); + const AST::PathIdentSegment &ident_seg = segment->get_ident_segment (); + bool is_first_segment = i == 0; + resolved_node_id = UNKNOWN_NODEID; + + bool in_middle_of_path = i > 0; + if (in_middle_of_path && segment->is_lower_self_seg ()) + { + // error[E0433]: failed to resolve: `self` in paths can only be used + // in start position + rust_error_at (segment->get_locus (), + "failed to resolve: %<%s%> in paths can only be used " + "in start position", + segment->as_string ().c_str ()); + return false; + } + + NodeId crate_scope_id = resolver->peek_crate_module_scope (); + if (segment->is_crate_path_seg ()) + { + // what is the current crate scope node id? + module_scope_id = crate_scope_id; + previous_resolved_node_id = module_scope_id; + resolver->insert_resolved_name (segment->get_node_id (), + module_scope_id); + + continue; + } + else if (segment->is_super_path_seg ()) + { + if (module_scope_id == crate_scope_id) + { + rust_error_at (segment->get_locus (), + "cannot use super at the crate scope"); + return false; + } + + module_scope_id = resolver->peek_parent_module_scope (); + previous_resolved_node_id = module_scope_id; + resolver->insert_resolved_name (segment->get_node_id (), + module_scope_id); + continue; + } + + switch (segment->get_type ()) + { + case AST::TypePathSegment::SegmentType::GENERIC: { + AST::TypePathSegmentGeneric *s + = static_cast (segment.get ()); + if (s->has_generic_args ()) + ResolveGenericArgs::go (s->get_generic_args ()); + } + break; + + case AST::TypePathSegment::SegmentType::REG: + // nothing to do + break; + + case AST::TypePathSegment::SegmentType::FUNCTION: + gcc_unreachable (); + break; + } + + if (is_first_segment) + { + // name scope first + NodeId resolved_node = UNKNOWN_NODEID; + const CanonicalPath path + = CanonicalPath::new_seg (segment->get_node_id (), + ident_seg.as_string ()); + if (resolver->get_type_scope ().lookup (path, &resolved_node)) + { + resolver->insert_resolved_type (segment->get_node_id (), + resolved_node); + resolved_node_id = resolved_node; + } + else if (resolver->get_name_scope ().lookup (path, &resolved_node)) + { + resolver->insert_resolved_name (segment->get_node_id (), + resolved_node); + resolved_node_id = resolved_node; + } + else if (segment->is_lower_self_seg ()) + { + // what is the current crate scope node id? + module_scope_id = crate_scope_id; + previous_resolved_node_id = module_scope_id; + resolver->insert_resolved_name (segment->get_node_id (), + module_scope_id); + + continue; + } + } + + if (resolved_node_id == UNKNOWN_NODEID + && previous_resolved_node_id == module_scope_id) + { + Optional resolved_child + = mappings->lookup_module_child (module_scope_id, + ident_seg.as_string ()); + if (resolved_child.is_some ()) + { + NodeId resolved_node = resolved_child->get_node_id (); + if (resolver->get_name_scope ().decl_was_declared_here ( + resolved_node)) + { + resolved_node_id = resolved_node; + resolver->insert_resolved_name (segment->get_node_id (), + resolved_node); + } + else if (resolver->get_type_scope ().decl_was_declared_here ( + resolved_node)) + { + resolved_node_id = resolved_node; + resolver->insert_resolved_type (segment->get_node_id (), + resolved_node); + } + else + { + rust_error_at (segment->get_locus (), + "Cannot find path %<%s%> in this scope", + segment->as_string ().c_str ()); + return false; + } + } + } + + bool did_resolve_segment = resolved_node_id != UNKNOWN_NODEID; + if (did_resolve_segment) + { + if (mappings->node_is_module (resolved_node_id) + || mappings->node_is_crate (resolved_node_id)) + { + module_scope_id = resolved_node_id; + } + previous_resolved_node_id = resolved_node_id; + } + else if (is_first_segment) + { + rust_error_at (segment->get_locus (), + "failed to resolve TypePath: %s in this scope", + segment->as_string ().c_str ()); + return false; + } + } + + if (resolved_node_id != UNKNOWN_NODEID) + { + // name scope first + if (resolver->get_name_scope ().decl_was_declared_here (resolved_node_id)) + { + resolver->insert_resolved_name (path.get_node_id (), + resolved_node_id); + } + // check the type scope + else if (resolver->get_type_scope ().decl_was_declared_here ( + resolved_node_id)) + { + resolver->insert_resolved_type (path.get_node_id (), + resolved_node_id); + } + else + { + gcc_unreachable (); + } + } + + return true; +} + +// qualified type paths + +ResolveRelativeQualTypePath::ResolveRelativeQualTypePath () + : failure_flag (false) +{} + +bool +ResolveRelativeQualTypePath::go (AST::QualifiedPathInType &path) +{ + ResolveRelativeQualTypePath o; + + // resolve the type and trait path + auto &qualified_path = path.get_qualified_path_type (); + if (!o.resolve_qual_seg (qualified_path)) + return false; + + // qualified types are similar to other paths in that we cannot guarantee + // that we can resolve the path at name resolution. We must look up + // associated types and type information to figure this out properly + + std::unique_ptr &associated + = path.get_associated_segment (); + + associated->accept_vis (o); + if (o.failure_flag) + return false; + + for (auto &seg : path.get_segments ()) + { + seg->accept_vis (o); + if (o.failure_flag) + return false; + } + + return true; +} + +bool +ResolveRelativeQualTypePath::resolve_qual_seg (AST::QualifiedPathType &seg) +{ + if (seg.is_error ()) + { + rust_error_at (seg.get_locus (), "segment has error: %s", + seg.as_string ().c_str ()); + return false; + } + + auto type = seg.get_type ().get (); + NodeId type_resolved_node = ResolveType::go (type); + if (type_resolved_node == UNKNOWN_NODEID) + return false; + + if (!seg.has_as_clause ()) + return true; + + NodeId trait_resolved_node = ResolveType::go (&seg.get_as_type_path ()); + if (trait_resolved_node == UNKNOWN_NODEID) + return false; + + return true; +} + +void +ResolveRelativeQualTypePath::visit (AST::TypePathSegmentGeneric &seg) +{ + if (seg.is_error ()) + { + failure_flag = true; + rust_error_at (seg.get_locus (), "segment has error: %s", + seg.as_string ().c_str ()); + return; + } + + ResolveGenericArgs::go (seg.get_generic_args ()); +} + +void +ResolveRelativeQualTypePath::visit (AST::TypePathSegment &seg) +{ + if (seg.is_error ()) + { + failure_flag = true; + rust_error_at (seg.get_locus (), "segment has error: %s", + seg.as_string ().c_str ()); + return; + } +} + +// resolve to canonical path + +bool +ResolveTypeToCanonicalPath::go (AST::Type *type, CanonicalPath &result) +{ + ResolveTypeToCanonicalPath resolver; + type->accept_vis (resolver); + result = resolver.result; + return !resolver.result.is_empty (); +} + +void +ResolveTypeToCanonicalPath::visit (AST::TypePath &path) +{ + NodeId resolved_node = UNKNOWN_NODEID; + if (!resolver->lookup_resolved_name (path.get_node_id (), &resolved_node)) + { + resolver->lookup_resolved_type (path.get_node_id (), &resolved_node); + } + + if (resolved_node == UNKNOWN_NODEID) + return; + + const CanonicalPath *type_path = nullptr; + if (mappings->lookup_canonical_path (resolved_node, &type_path)) + { + auto &final_seg = path.get_segments ().back (); + switch (final_seg->get_type ()) + { + case AST::TypePathSegment::SegmentType::GENERIC: { + AST::TypePathSegmentGeneric *s + = static_cast (f